<template>
  <el-dialog :title="props.title" width="1200px" v-model="dialogVisible" :before-close="onClose">
    <div class="config">
      <el-form ref="ruleFormRef" label-width="auto"
        style="display: flex;width: 100% !important;flex-wrap: wrap;min-height: 140px;max-height: calc(100vh - 300px);"
        :model="info" :disabled="!props.savebtn" label-position="right" :rules="rules" label-suffix=":" :inline="true">
        <el-form-item label="值班日期" prop="day" style="width: 100%;">
          <el-input v-model="info.day" disabled style="width: 100%;" />
        </el-form-item>
        <el-form-item label="选择部门" style="width: 100%;">
          <el-button type="primary" @click="chooseBm" :disabled="addBmDisBtn">添加部门</el-button>
        </el-form-item>
        <div v-if="bmList && bmList.length > 0">
          <div v-for="(item, index) in bmList" :key="index">
            <el-divider>{{ item.deptname }}</el-divider>
            <div style="display: flex;align-items: center;">
              <el-form-item label="部门" prop="orgName">
                <el-input v-model="item.deptname" disabled style="width: 200px;" />
              </el-form-item>
              <el-button style="margin-bottom: 18px;" type="danger" @click="delBm(index)">删除部门</el-button>
              <!-- <el-button v-if="isEdit" style="margin-bottom: 18px;" type="danger" @click="eidtBm(index)">选择部门</el-button> -->
            </div>
            <div>
              <el-form-item label="值班人员" prop="username">
                <div style="display: flex;align-items: end;">
                  <el-input v-model="item.username" type="textarea" style="width: 990px;" :rows="4" readonly>
                  </el-input>
                  <el-button style="margin-left: 5px;" type="primary" @click="chooseRy(item, index)">选择人员</el-button>
                </div>
              </el-form-item>
            </div>
          </div>


        </div>
      </el-form>

      <div>

      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">

        <el-button type="primary" style="margin-right: 16px;" v-loading="loadingShow" @click="onSave"
          v-if="props.savebtn"> <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span> </el-button>
        <el-button @click="onClose"> <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span></el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 部门 -->
  <Choosebm :showDdld="showDept" @closezzjg="closezzjg" @listdata="bmChange" :zzlx="zzlx" :searchType="'01'"
    :deptId='deptIdbm' :Isstrictly="false" />
  <!-- 选择责任人 -->
  <ChooseUser v-model="chooseUserVisible" :Single="false" @choosedUsers="getSonValue" :deptId="currDept.deptid"
    :data="memberList"> </ChooseUser>
  <!-- 选择部门 -->
  <!-- <dwhasbjMult :showDdld="showDept" @closezzjg="closezzjg" Isstrictly :deptId="deptIdbm" v-model="bmList"
      searchType="03" @listdata="bmChange" /> -->
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, computed } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
import { getItem } from "@/utils/storage.js";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue"
import dwhasbjMult from "@/components/MyComponents/ChooseDept/dwhasbjMult.vue";

const { proxy } = getCurrentInstance();
// 数据

const props = defineProps({
  title: String,
  id: String,
  savebtn: Boolean,
  isDetail: {
    type: Boolean,
    default: false
  },
  rowItem: {
    type: Object,
    default: () => ({})
  },
  zbFrom: {
    type: Object,
    default: () => ({})
  },
});
const emits = defineEmits(["closeDetail"]);
/** 添加部门dis */
const addBmDisBtn = computed(() => {
  if (!props.savebtn) return true
  if (props.id && bmList?.value?.length) return true
})
const dialogVisible = ref(true);
const loadingShow = ref(false)
const ruleFormRef = ref()
const info = ref({})
const showDept = ref(false)
const deptIdbm = ref(getItem('deptId').ssdwid)
const zzlx = ref(null)
const memberList = ref([])
const currDept = ref({})
const isEdit = ref(props.savebtn && props.id)
const isAdd = ref(props.savebtn && !props.id)
/** 选中的部门 */
const bmList = ref([])
//选择人员弹窗
const chooseUserVisible = ref(false)
const rules = ref({
  orgName: [{
    required: true, message: "请选择部门", trigger: "blur", validator: (rule, value, callback) => {
      // if (!value) {
      //   return callback(new Error("请输入企业名称"));
      // } else {
      // }
      callback();
    }
  }],
  username: [{
    required: true, message: "请选择值班人员", trigger: "change", validator: (rule, value, callback) => {
      // console.log('value: ', value);
      // if (!value) {
      //   return callback(new Error("请选择人员"));
      // } else {
      //   callback();
      // }
      callback();
    }
  }],
  riskEvaluateTypeCode: [{ required: true, message: "请选择风险评价类型", trigger: "blur" }],
  riskUnitLevelCode: [{ required: true, message: "请选择风险单元等级", trigger: "blur" }],
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "riskUnitQty")
});
onMounted(() => {
  if (props.id) {
    // getDetail()
    if (props.savebtn) {
      bmList.value = [{
        deptid: props.rowItem.deptid,
        deptname: props.rowItem.deptname,
        username: props.rowItem.username,
        userid: props.rowItem.userid
      }]
    } else {
      bmList.value = [{
        deptid: props.rowItem.deptid,
        deptname: props.rowItem.deptname,
        username: props.rowItem.username,
        userid: props.rowItem.userid
      }]
    }
  }

  info.value.day = props.zbFrom.day
});
const onClose = () => {
  if(!ruleFormRef.value) return
  if (props.savebtn) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emits('closeDetail')
      })
      .catch(() => {
        // catch error
      })
  } else {
    emits('closeDetail')
  }

};
const chooseRy = (item, index) => {
  console.log('item: ', item);
  // zzlx.value = "01"
  currDept.value = item
  memberList.value = item.userid ? item.userid.split(',') : []
  chooseUserVisible.value = true
}
const getSonValue = (value) => {
  console.log('value: ', value);
  value = Array.isArray(value) ? value : []
  currDept.value.username = value.map(item => item.userName).join(',')
  currDept.value.userid = value.map(item => item.id).join(',')
  chooseUserVisible.value = false
}
const onSave = async () => {
  // loadingShow.value = true
  if (!bmList.value.length) {
    ElMessage.warning('请选择部门！！！')
    return
  }
  if (bmList.value.some(item => !item.username)) {
    ElMessage.warning('请选择值班人员！！！')
    return
  }
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      console.log('bmList.value: ', bmList.value);


      if (!props.rowItem?.id) {
        let params = {
          day: props.zbFrom.day,
          deptList: bmList.value
        }
        loadingShow.value = true
        postApi(params, "/mosty-jcgl/onDuty/saveDuty")
          .then(res => {
            ElMessage({
              message: "新增成功",
              type: "success"
            })
            emits("closeDetail", true)
          })
          .finally(() => {
            loadingShow.value = false
          })
      } else {
        loadingShow.value = true
        let one = bmList.value[0] || {}
        let params = {
          day: props.zbFrom.day,
          deptid: one.deptid,
          deptname: one.deptname,
          username: one.username,
          userid: one.userid,
          id: props.rowItem.id
        }
        postApi(params, "/mosty-jcgl/onDuty/editDuty")
          .then((res) => {
            ElMessage({
              message: "修改成功",
              type: "success"
            });
            emits("closeDetail", true);
          })
          .finally(() => {
            loadingShow.value = false
          });
      }

    } else {
      ElMessage.warning('请输入必填项！！！')
      loadingShow.value = false
    }
  });
}
//关闭弹窗
const closezzjg = (val) => {
  showDept.value = val;
};
const bmChange = (val) => {
  if (val.length == 0) return;
  // 相同部门不添加
  if (bmList.value.some(item => item.deptid == val.orgCode)) {
    ElMessage.warning('部门已存在！')
    return
  }
  bmList.value.push({
    deptid: val.orgCode,
    deptname: val.orgName,
  })
};
const chooseBm = () => {
  showDept.value = true;
}
const delBm = (index) => {
  bmList.value.splice(index, 1)
}
const getDetail = () => {
  // let _url = props.isDetail ? "/data/riskUnitDist/getDetailById" : "/data/riskUnitDist/getLsjlDetail"
  // getApi({ id: props.id }, `/mosty-jcgl${_url}`)
  //   .then((res) => {
  //     info.value = res
  //   })
}

</script>

<style lang="scss" scoped>
.config {
  width: 740px;
}

.content {
  .topper {
    display: flex;

    .sub-le {
      flex: 1;
      padding: 15px 15px 5px 15px;
      border-right: 1px solid #ebeef5;
    }
  }

  .bottom {
    padding: 0 15px 10px 15px;
  }
}
</style>
