<template>
  <div class="step3-container">
    <el-form ref="fromRef" :model="formData" :rules="rules" label-width="200px"
      style="display: block; width: 96%; max-height: 72vh" :inline="true" label-suffix="：">
      <el-form-item label="单位" style="width: 96%;">

        <el-button type="primary" @click.stop="ChooesDdld(1)">选择单位</el-button>
        <div>
          <el-tag type="success" v-for="dept in allDeptList" :key="dept.id">{{ dept.orgName }}</el-tag>
        </div>
      </el-form-item>
      <template v-for="(dept, index) in allDeptList" :key="dept.id">
        <el-divider>{{ dept.orgName }}</el-divider>

        <div style="width:95%">
          <el-form-item label="是否根据岗位层级随机筛选" style="width: 320px;">
            <el-radio-group style="width: 100%" v-model="dept.isTypeFlag" @change="changeSflx($event, dept, index)">
              <el-radio label="1">是</el-radio>
              <el-radio label="2">否</el-radio>
            </el-radio-group>

          </el-form-item>
          <el-button v-if="dept.isTypeFlag == 1" style="margin-left: 5px;width: 7.5em;margin-bottom:18px" type="primary"
            @click.stop="addPost(dept, dept.postArr.length)">添加岗位层级</el-button>
        </div>
        <el-form-item v-if="dept.isTypeFlag == 2" label="参加人数" style="width: 45%;">
          <el-input-number v-model="dept.total" :step="1" precision="0" :min="1" placeholder="参加人数"></el-input-number>
        </el-form-item>
        <div v-else class="position-container">

          <div style="width: 45%;border: 1px solid #ccc;padding: 10px;margin: 10px"
            v-for="(postItem, postIdx) in dept.postArr" :key="postIdx">
            <el-form-item label="岗位层级" style="width: 100%;" label-width="7.5em">
              <!-- <el-input v-model="postItem.positionName" readonly placeholder="请选择岗位"
                @click="choosePosition(postItem, postIdx, dept, index)"></el-input> -->
              <el-select v-model="postItem.type" placeholder="请选择岗位层级"
                @change="changePosition($event, postItem, postIdx, dept, index)">
                <el-option v-for="item in D_BZ_SSJFW" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="单位类型" style="width: 100%;" label-width="7.5em">
              <el-radio-group v-model="postItem.unit" @change="changeUnit(postItem, postIdx)">
                <el-radio label="1">数量</el-radio>
                <el-radio label="2">比例</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="数量/比例" style="width:100%;" label-width="7.5em">
              <el-input style="width: calc(100% - 45px)" v-model="postItem.num" type="number"
                :max="postItem.unit == '1' ? 99999999 : 100" placeholder="数量" @change="changeNum(postItem, postIdx)">
                <template #append>{{ postItem.unit == '1' ? '人' : '%' }}</template>
              </el-input>
              <!-- 删除 -->
              <el-button title="删除岗位" style="margin-left: 5px;width: 30px;" type="danger" :icon="Delete"
                @click="deletePost(dept, index, postItem, postIdx)" />
              <!-- <el-button style="margin-left: 5px;width: 80px;" type="primary"
                @click="addPost(dept, index)">添加岗位</el-button> -->
            </el-form-item>

          </div>

        </div>
      </template>

    </el-form>
    <!-- 选择部门 -->
    <dwhasbjMult :showDdld="showDept" @closezzjg="closezzjg" Isstrictly :deptId="deptId" v-model="selectData"
      searchType="03" @listdata="getSonValues" />
    <!-- 岗位选择 -->
    <Gwxz v-model="showGwxz" @change="changeGwxz" />
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  defineProps,
  defineEmits,
  reactive,
  getCurrentInstance,
  defineExpose,
} from "vue";
import { ElMessage } from 'element-plus';
// import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import dwhasbjMult from "@/components/MyComponents/ChooseDept/dwhasbjMult.vue";
import {
  Delete,
} from '@element-plus/icons-vue'
// import { getItem } from "@/utils/storage";
// import * as MOSTY from "@/components/MyComponents/index";
import Gwxz from "@/views/systemConfig/user-list/components/Gwxz.vue";
const { proxy } = getCurrentInstance();
const { D_BZ_SF, D_BZ_SSJFW } = proxy.$dict("D_BZ_SF", "D_BZ_SSJFW");
/** 表单ref */
const fromRef = ref();
/** 搜索类型 */
const searchType = ref('03')
/** 选中的部门数据 */
const selectData = ref([])
/** 部门id */
const deptId = ref()

/** 所有选中的单位数组 */
const allDeptList = ref([])
/** 当前选中的岗位 */
const currPostItem = ref({})
/**表单数据 */
const formData = ref({
  // deptId: '',
  // sflx: '1',
});
/** 是否显示选择部门 */
const showDept = ref(false)
/** 部门信息 */
const formInfo = ref()
/** 是否显示选择岗位 */
const showGwxz = ref(false)
/** 当前选中的部门索引 */
const currDeptIndex = ref(0)
/**表单校验 */
const rules = reactive({
  // startTime: [{ trigger: "change", required: true, message: "请选择开始时间" }],
  // endTime: [{ trigger: "change", required: true, message: "请选择结束时间" }],
  // sfckct: [{ trigger: "change", required: true, message: "请选择是否查看错题" }],
  // sflx: [{ trigger: "change", required: true, message: "请选择是考题是否随机" }],
});


/** 选择单位 */
const ChooesDdld = () => {
  showDept.value = true
}
/** change -是否根据[类型]随机筛选
 * @param {string} val 选中值 1:是 2:否
 * @param {object} dept 当前部门
 * @param {number} index 当前部门索引
 */
const changeSflx = (val, dept, index) => {
  if (val == '1') { // 是
    dept.postArr = [{ type: '', unit: '1', num: '' }]
  } else { // 否
    dept.postArr = []
  }
  currDeptIndex.value = index
}
/** 岗位层级下拉-修改 */
const changePosition = (val, postItem, postIdx, dept, index) => {
  let postArr = dept.postArr
  let sameType = postArr.some((item, i) => item.type == val && i != postIdx)
  if (sameType) {
    ElMessage.warning('岗位层级不能重复!')
    postItem.type = ''
    return
  }
  const options = Array.isArray(D_BZ_SSJFW.value) ? D_BZ_SSJFW.value : []
  const label = options.find(item => item.value == val)?.label
  // postItem.type = val // 上面已经双向绑定
  postItem.positionName = label
}
/** 选择岗位-点击 */
const choosePosition = (postItem, postIdx, dept, index) => {
  currPostItem.value = postItem
  // currPostIdx.value = postIdx
  showGwxz.value = true
  // currDeptIndex.value = index
}
/**选中岗位 */
const changeGwxz = (val) => {
  currPostItem.value.positionName = val.name
  currPostItem.value.type = val.id
  showGwxz.value = false
}
/** 单位类型修改 */
const changeUnit = (postItem, postIdx) => {
  postItem.num = ''
}
/** 数量修改 */
const changeNum = (postItem, postIdx) => {
  if (postItem.unit == '2') {
    if (postItem.num > 100) {
      postItem.num = '100'
      ElMessage.warning('比例不能超过100%')
    }
    if (postItem.num < 0) {
      postItem.num = '0'
      ElMessage.warning('比例不能小于0%')
    }
  } else {
    if (postItem.num < 0) {
      postItem.num = '0'
      ElMessage.warning('数量不能小于0')
    } else if(postItem.num > -1){
      postItem.num = parseInt(postItem.num)
    }
  }
}
/** 添加岗位 */
const addPost = (dept, index) => {
  // if (dept.postArr.length >= D_BZ_SSJFW?.value?.length) {
  //   ElMessage.warning(`最多添加${D_BZ_SSJFW?.value?.length}个岗位层级`)
  //   return
  // }
  dept.postArr.splice(index + 1, 0, { type: '', unit: '1', num: '' })
}
/** 删除岗位 */
const deletePost = (dept, index, postItem, postIdx) => {
  if (dept.postArr.length == 1) {
    ElMessage.warning('至少保留一个岗位')
    return
  }
  dept.postArr.splice(postIdx, 1)
}
//获取部门信息
const getSonValues = async (val) => {

  // allDeptNameStr.value = val.map(item => item.orgName).toString()
  allDeptList.value = val.map(item => {
    return {
      // ...item,
      orgId: item.id,
      orgName: item.orgName,
      isTypeFlag: '2',
    }
  })

}
//关闭弹窗
const closezzjg = (val) => {
  showDept.value = val;
};

/** 获取表单数据 */
const getFormData = () => {

  let examPeopleRandomList = allDeptList.value.map(item => {
    /** 岗位数组 */
    let postArr = Array.isArray(item.postArr) ? item.postArr : []

    return {
      orgId: item.orgId,
      total: item.total,
      isTypeFlag: item.isTypeFlag,
      typeList: item.isTypeFlag == '1' ? postArr : [],
    }
  })

  return { examPeopleRandomList }
}
/** 校验数据 */
const check = () => {
  // fromRef.value.validate()
  if (allDeptList.value.length == 0) {
    ElMessage.warning('请选择单位')
    return false
  }
  // if (allDeptList.value.some(item => item.postArr.length == 0)) {
  //   ElMessage.warning('请添加岗位')
  //   return false
  // }
  if (allDeptList.value.some(item => item.isTypeFlag == '2' && !item.total)) {
    ElMessage.warning('请输入参加人数')
    return false
  }
  // 请选择岗位
  if (allDeptList.value.some(item => item.isTypeFlag == '1' && item.postArr.some(post => !post.type))) {
    ElMessage.warning('请选择岗位')
    return false
  }
  if (allDeptList.value.some(item => item.isTypeFlag == '1' && item.postArr.some(post => !post.num))) {
    ElMessage.warning('请输入岗位数量/比例')
    return false
  }


  return true
};
defineExpose({
  check,
  getFormData
});
</script>

<style scoped lang="scss">
.step3-container {
  display: flex;
  justify-content: center;
  height: 100%;
  padding-top: 20px;
}

.position-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

}
</style>
