<template>
  <!-- 添加同行人 -->
  <el-dialog title="添加同行人" :visible.sync="dialogVisible" width="400px" :before-close="handleCancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px" label-position="top">
      <el-row v-for="(item,index) in form.tripPartners" :key="index">
        <el-form-item label="部门" :prop="`tripPartners.${index}.dpt`" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
          <el-cascader v-model="item.dpt" filterable class="wd100" size="small" clearable :options="deptOptions" :props="defaultProps" @change="handleChange($event,index)"></el-cascader>
        </el-form-item>
        <el-form-item label="同行人" :prop="`tripPartners.${index}.userId`" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
          <el-select v-model="item.userId" clearable multiple filterable class="wd100" size="small">
            <el-option v-for="item in item.userList" :key="item.id" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>
        <div class="del-box" v-if="form.tripPartners.length > 1">
          <el-button type="text" plain @click="handleDel(index)" icon="el-icon-delete">删除</el-button>
        </div>
      </el-row>
      <el-row>
        <div class="add-box">
          <el-button type="primary" plain @click="handleAdd" size="small" icon="el-icon-plus">增加</el-button>
        </div>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { listSimpleDepts } from "@/api/system/dept";
import {
  listUser,
} from "@/api/system/user";
export default {
  //import引入组件才能使用
  props: {
    isOpen: Boolean,
    selectUserIds: Array,
  },
  components: {},
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "name",
        value: 'id',
        emitPath: false,
        checkStrictly: true
      },
      userList: [],
      deptOptions: [],
      dialogVisible: false,
      form: {
        tripPartners: [
          {
            dpt: null,
            userId: [],
            userList: [],
          }
        ]
      },
      rules: {
        dpt: [
          { required: true, trigger: "change", message: "请选择" }
        ],
        userId: [
          { required: true, trigger: "change", message: "请选择" }
        ],
      }
    };
  },
  // 计算属性
  computed: {},
  // 监听data中的数据变化
  watch: {
    isOpen: {
      handler(val) {
        this.dialogVisible = val
        if (val) {
          this.$nextTick(() => {
            this.$refs.form.resetFields()
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  // 方法集合
  methods: {
    //判断数组元素是否有重复
    getisRepeat(arr) {
      var ary = arr;
      var nary = ary.sort();
      for (var i = 0; i < ary.length; i++) {
        if (nary[i] == nary[i + 1]) {
          return nary[i]
        }
      }
    },
    /** 查询用户列表 */
    getList(id) {
      return new Promise((resolve) => {
        let queryParams = {
          pageNo: 1,
          pageSize: 100,
          username: undefined,
          mobile: undefined,
          status: undefined,
          deptId: id,
          createTime: []
        }

        listUser(queryParams).then(response => {
          this.userList = response.data.list || [];
          this.$emit('onList', this.userList)
          resolve(this.userList)
        })
      })
    },
    handleResetCoursePacketId() {
      this.listQuery.coursePacketIds.forEach((v => {
        this.handleFilterList(v.omOrderCoursePacketId).then(res => {
          this.$set(v, 'coursePacketList', res)
        })
      }))
    },

    // 过滤数组 // type 1 删除 其他 变更或者增加
    handleFilterList(list, type, id) {
      return new Promise((resolve) => {
        // let arr = (this.form.tripPartners.map(v => v.userId)).map(item => item)
        let arr = []
        this.form.tripPartners.forEach((v, i) => {
          v.userId && v.userId.length && v.userId.forEach(n, z => {
            arr.push(n)
          })
        })
        if (!type) {
          resolve(list.filter(v => !arr.includes(v.id) || v.id == id) || [])
        } else {

        }
        console.log('arrr..', arr);
        // if (!id) {
        //   resolve(this.applyBaseInfo.coursePacketIds.filter(v => !arr.includes(v.id)) || [])
        // } else {
        //   resolve(this.applyBaseInfo.coursePacketIds.filter(v => !arr.includes(v.id) || v.id == id) || [])
        // }
      })
    },
    handleDel(index) {
      this.form.tripPartners.splice(index, 1)
    },
    handleAdd() {
      this.form.tripPartners.push({ dpt: null, userId: [], userId: [] })
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      listSimpleDepts().then(response => {
        // 处理 deptOptions 参数
        this.deptOptions = [];
        this.deptOptions.push(...this.handleTree(response.data, "id"));
        this.$emit('onDept', this.deptOptions)
        this.deptOptions && this.deptOptions.length && this.getList(this.deptOptions[0].id)
      });
    },
    handleChange(val, index, userId) {
      console.log('val...', val, index)
      this.getList(val).then((list) => {
        this.$set(this.form.tripPartners[index], 'userList', list)
        this.$set(this.form.tripPartners[index], 'userId', [])
      })
    },
    handleCancel() {
      this.$emit('onCancel')
    },
    handleConfirm() {
      this.$nextTick(() => {
        this.$refs.form.validate((bool) => {
          if (bool) {
            let arr = []
            this.form.tripPartners.forEach((n) => {
              n.userId.forEach((z) => {
                arr.push(z)
              })
            })
            let repeatId = this.getisRepeat(arr)
            if (repeatId) {
              const { username } = this.userList.find(item => item.id == repeatId) || {}
              this.$modal.msgError(`同行人${username}已经被添加，请勿重复添加！`);
            } else {

              this.$emit('onConfirm', arr)
            }
          }
        })
      })
    }
  },
  // 生命周期，创建完成时（可以访问当前this实例）
  created() {
    this.getTreeselect()
  },
  // 生命周期：挂载完成时（可以访问DOM元素）
  mounted() {

  },
}
</script>
<style lang="scss"  scoped>
::v-deep .el-form--label-top .el-form-item__label {
  padding: 0px;
}
::v-deep .el-form-item {
  margin-bottom: 10px !important;
}
.el-row {
  position: relative;
}
.del-box {
  position: absolute;
  right: 0;
  top: 0;
}
.add-box {
  display: flex;
  justify-content: center;
}
</style>