<template>
  <div>
    <el-dialog title="检查小组新增" width="1080px" v-if="props.addShow" v-model="props.addShow" :before-close="closeDialog">
      <el-form :model="fromObj" ref='fromref' :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize"
        status-icon>
        <el-form-item label="带队领导:" prop="leadername">
          <el-input v-model="fromObj.leadername" readonly>
            <template #append>
              <el-button class='cursor' @click="ChooesDdld('01')">选择</el-button></template>
          </el-input>
        </el-form-item>
        <el-form-item label="检查组长:" prop="zzxm">
          <el-input v-model="fromObj.zzxm" readonly>
            <template #append>
              <el-button class='cursor' @click="ChooesDdld('02')">选择</el-button></template>
          </el-input>
        </el-form-item>
        <el-form-item label="检查成员:" prop="userListName">
          <el-input v-model="fromObj.userListName" readonly>
            <template #append>
              <el-button class='cursor' @click="ChooesDdld('03')">选择</el-button></template>
          </el-input>
        </el-form-item>
        <el-form-item label="检查范围:" prop="taskListName">
          <el-input v-model="fromObj.taskListName" readonly>
            <template #append>
              <el-button class='cursor' @click="ChooesDdld('04')">选择</el-button></template>
          </el-input>
        </el-form-item>
        <el-form-item label="注意事项:">
          <el-input v-model="fromObj.zysx" autosize clearable style="width: 100%" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" v-loading='loadingshow' @click="handleSave(fromref)">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button @click="closeDialog" type="primary">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 选择带队领导 -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
      @choosedUsers="getSonValue"></ChooseUser>
    <!-- <dwhasbjMult :data="taskList" :showDdld="showJkssbm" :searchType="'03'" @closezzjg="closeJhss" :Isstrictly='true'
      @listdata="getSonValue" :zzlx="zzlx" /> -->
    <dwhasbjMult :showDdld="showJkssbm" @closezzjg="closeJhss" Isstrictly :deptId="deptId" v-model="taskList"
      searchType="03" @listdata="getSonValue" />
  </div>
</template>

<script setup>
// 引入
import { defineProps, onMounted, reactive, watch, ref, defineEmits, getCurrentInstance, nextTick } from "vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
// import ChooseDept from "@/components/MyComponents/ChooseDept/Departnobj.vue";
import dwhasbjMult from "@/components/MyComponents/ChooseDept/dwhasbjMult.vue";
import { ElMessage } from "element-plus";
import { getErrMsg } from '@/utils/tools.js'


const { proxy } = getCurrentInstance();
const rules = reactive({
  // leadername: [{ required: true, message: "请选择带队领导", trigger: "change" }],
  zzxm: [{ required: true, message: "请选择检查组长", trigger: "change" }],
  userListName: [{ required: true, message: "请选择检查成员", trigger: "change" }],
  taskListName: [{ required: true, message: "请选择检查范围", trigger: "change" }],

});
const loadingshow = ref(false)
const fromref = ref()
const showXzcy = ref(false);
const zzlx = ref(null);
const singleShow = ref(true); //单选多选
const deptId = ref();
const props = defineProps({
  addShow: {
    type: Boolean,
    default: false
  },
  fromObj: Object,
  /**检查组-数组 */
  jczList: Array,
  /**编辑的索引 */
  editIndex: Number,
});

watch(
  () => props.fromObj,
  (val) => {
    if (val) {
      fromObj.value = JSON.parse(JSON.stringify(props.fromObj));
    } else {
      fromObj.value = {
        userList: [],
        zzxm: '',
        userListName: '',
        taskListName: '',
      };
    }
  }
);
const chooseUserVisible = ref(false);
const fromObj = ref({
  userList: [],
  userListName: '',
  zzxm: '',
  taskListName: '',
});
// 表格回显的id
const leaderid = ref("");
/** 检查范围数组 */
const taskList = ref([]);
const memberList = ref([]); //成员选择的id回显
const showDdld = ref(false);
const showJkssbm = ref(false); //选择部门
//点击带队领导选择按钮
function ChooesDdld(val) {
  zzlx.value = val;
  if (val == "01" || val == "02") {
    leaderid.value = "";
    if (val == "01") {
      leaderid.value = fromObj.value.leaderid;
    } else {
      leaderid.value = fromObj.value.zzid;
    }
    singleShow.value = true;
    chooseUserVisible.value = true;
  } else if (val == "04") {
    // 检查范围用作表格回显
    if (fromObj.value.taskList != null) {
      taskList.value = fromObj.value.taskList
    } else {
      taskList.value = [];
    }
    showJkssbm.value = true;
    // 检查成员 03
  } else {
    // 成员list用作表格回显
    if (fromObj.value.userList) {
      memberList.value = fromObj.value.userList.map((item) => {
        return item.userId;
      });
    } else {
      memberList.value = [];
    }
    chooseUserVisible.value = true;
    singleShow.value = false;
  }
}
const closeJhss = (val) => {
  showJkssbm.value = val;
};

const emits = defineEmits(["changeclose", "getList"]);

onMounted(() => {
});

/** 带队领导 是否重复 */
const checkLeaderRepeat = (val) => {
  if (!props.jczList?.length) return true
  /** 除自身外的其他内容 */
  const otherArr = props.jczList.filter((item, i) => props.editIndex !== i)
  const repeatIdx = otherArr.findIndex((item) => item.leaderid == val.id)
  if (repeatIdx > -1) {
    ElMessage.warning(`带队领导重复！重复位置第【${repeatIdx + 1}】行`);
    return false;
  }
  return true;
};
/** 是否检查组长是否重复 */
const checkJczzRepeat = (val) => {
  if (!props.jczList?.length) return true
  /** 除自身外的其他内容 */
  const otherArr = props.jczList.filter((item, i) => props.editIndex !== i)
  const repeatIdx = otherArr.findIndex((item) => item.zzid == val.id)
  if (repeatIdx > -1) {
    ElMessage.warning(`与第【${repeatIdx + 1}】组，检查组长重复！`);
    return false;
  }
  return true;
};

/** 是否检查【成员】是否重复
 * @param { Array } val
 */
const checkCyRepeat = (val) => {
  if (!props.jczList?.length) return true
  /** 除自身外的其他内容 */
  const otherArr = props.jczList.filter((item, i) => props.editIndex !== i)
  const cyIds = val.map((item) => item.id)
  /**重复人员 */
  let cyName = ''
  const repeatIdx = otherArr.findIndex((item) => {
    return item.userList.findIndex((cy) => {
      if (cyIds.includes(cy.userId)) {
        cyName = cy.userName
        return true
      }
    }) > -1
  })
  if (repeatIdx > -1) {
    ElMessage.warning(`与第【${repeatIdx + 1}】行，检查成员【${cyName}】重复！`);
    return false;
  }
  return true;
};
/**
 *
 * @param {Array} val 判断要添加的是否重复
 * @param type 类型  01 带队领导 02 检查组长 03 检查成员
 */
const checkReapt = (val, type) => {
  const obj = {}
  if (!props.jczList?.length) return true
  props.jczList.forEach((item, i) => {
    if (props.editIndex !== i) {
      const { zzid, leaderid, userList } = item || {}
      obj[zzid] = { sort: i, label: '检查组长' }
      obj[leaderid] = { sort: i, label: '带队领导' }
      if (userList?.length > 0) {
        userList.forEach((cy) => {
          obj[cy.userId] = { sort: i, label: '检查成员', userName: cy.userName }
        })
      }
    } else {
      const { zzid, leaderid, userList } = item || {}
      if (type !== '01') obj[leaderid] = { sort: i, label: '带队领导' }
      if (type !== '02') obj[zzid] = { sort: i, label: '检查组长' }
      if (type !== '03' && userList?.length > 0) {
        userList.forEach((cy) => {
          obj[cy.userId] = { sort: i, label: '检查成员', userName: cy.userName }
        })
      }
    }
  })
  const isHave = val.some((item) => {
    if (obj[item.id]) {
      const curr = obj[item.id]
      if (props.editIndex === curr.sort) {
        ElMessage.warning(`【${obj[item.id].label}】已存在【${item.userName}】！`);
      } else {
        ElMessage.warning(`【第${obj[item.id].sort + 1}组】【${obj[item.id].label}】已存在【${item.userName}】！`);
      }
    }
    if (obj[item.id]) return true
  })
  return !isHave

};
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    const isLeaderRepeat = checkLeaderRepeat(value[0]); // 带队领导是否重复
    if (!isLeaderRepeat) return;
    fromObj.value.leadername = value[0].userName;
    fromObj.value.leaderid = value[0].id;
    fromObj.value.leaderOrgcode = value[0].deptId;
  } else if (zzlx.value == "02") {
    /**检查小组是否重复 */
    const isJczzRepeat = checkJczzRepeat(value[0]);
    if (!isJczzRepeat) return;
    fromObj.value.zzxm = value[0].userName;
    fromObj.value.zzid = value[0].id;
    fromObj.value.zzOrgcode = value[0].deptId;
  } else if (zzlx.value == "03") {
    const isCyRepeat = checkCyRepeat(value); // // 成员是否重复
    if (!isCyRepeat) return;
    let arr = [];
    for (let i = 0; i < value.length; i++) {
      const element = value[i];
      element.zzlx = zzlx.value;
      arr.push(element.userName);
    }
    memberList.value = value.map((item) => {
      return item.id;
    });
    fromObj.value.userList = value.map((item) => {
      return {
        userId: item.id,
        userName: item.userName
      };
    });
    fromObj.value.userListName = arr.join(",");
  } else if (zzlx.value == "04") {
    let userarr = [];
    for (let i = 0; i < value.length; i++) {
      const element = value[i];
      userarr.push(element.orgName);
    }
    fromObj.value.taskList = value.map((item) => {
      return item.id;
    });
    // taskList.value = value.map((item) => {
    //   return item.id;
    // });
    // fromObj.value.taskList = value.map((item) => {
    //   return {
    //     orgid: item.orgCode,
    //     orgname: item.orgName
    //   };
    // });
    fromObj.value.taskListName = userarr.join(",");
  }

  //   sonMessage.value = value
};



// 方法
//关闭弹窗
const closezzjg = (val) => {
  showDdld.value = val;
  showXzcy.value = false;
};

const closeDialog = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      emits("changeclose", false);
    })
    .catch(() => {
      // catch error
    })

};
const handleSave = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loadingshow.value = true
      if (fromObj.value) {
        emits("getList", fromObj.value);
        emits("changeclose", false);
        loadingshow.value = false
      }

    } else {
      ElMessage.warning(getErrMsg(fields) || '请输入必填项！！！!')
    }
  })
};
</script>

<style lang="scss" scoped>
.el-form {
  padding: 10px;
  margin-top: 10px;
  flex-wrap: wrap;
  justify-content: space-between;
}

.el-form-item {
  text-align: center;
  width: 990px;
}

.flx {
  display: flex;
  width: 100%;

  .el-button {
    margin-left: 10px;
  }
}

.titleBox {
  align-items: center;
  padding: 20px;
  border: 1px solid rgb(32, 75, 54);
}

.content {
  margin-top: 50px;

  div {
    margin-bottom: 20px;
  }
}

.one {
  display: flex;
  width: 100%;
  justify-content: space-between;

  div {
    width: 32%;
    display: flex;

    // align-items: center;
    .el-input {
      width: 60%;
    }
  }
}

.two {
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    width: 15%;
  }
}
</style>
