<template>
  <div>
    <div class="bigBox">
      <MOSTY.FromPage title="批量签订责任书" @closeDialog="handleClose">
        <template #content>
          <div class="box-big">
            <div class="box-left">
              <el-form class="elfrom" ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="130px"
                :disabled="props.isdisabled" :inline="true" style="display: block;">
                <el-form-item label="责任书名称:" prop="zrsmc">
                  <el-input v-model="ruleForm.zrsmc" clearable style="width: 646px"></el-input>
                </el-form-item>
                <el-form-item label="责任书类型:" prop="lxs" style='width:100%;'>
                  <el-radio-group v-model="ruleForm.lxs" size="small" @change="changeLxs" :disabled='ISbj'>
                    <el-radio v-for="item in zslxlist" :value="item.value" :key="item.value" :label="item.value"
                      border>{{ item.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item :label="fqText + ':'" prop="fqdwid">
                  <el-input v-model="ruleForm.fqdwmc" readonly clearable style="width:260px" disabled>
                    <template #append>
                      <el-button disabled>选择</el-button>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="审批领导：" label-width="100px">
                  <el-input v-model="ruleForm.ldxm" readonly clearable style="width:260px" disabled>
                    <template #append>
                      <el-button @click="inputClick('02')" :disabled='ISbj'>选择</el-button>
                    </template>
                  </el-input>
                </el-form-item>
                <div>
                  <el-form-item :label="bqdText + ':'" prop="rydwid">
                    <el-input v-model="ruleForm.rydwmc" clearable readonly style="width:260px"
                      :placeholder="'请选择' + bqdText" :disabled='ISbj || bisab'>
                      <template #append>
                        <el-button @click="ChooesDdld" :disabled='ISbj || bisab'>选择</el-button>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="签订人：" prop="ryxm" label-width="100px">
                    <el-input v-model="ruleForm.ryxm" placeholder="请选择签订人" readonly clearable style="width:260px"
                      :disabled='ISbj'>
                      <template #append>
                        <el-button @click="inputClick('01')" :disabled='ISbj'>选择</el-button>
                      </template>
                    </el-input>
                  </el-form-item>
                </div>
                <MOSTY.Assort title="批量设置" />
                <template v-if="ruleForm.user.length === 0 || ruleForm.user.length != ruleForm.chooseUser.length">
                  <el-form-item label="安全责任清单:" prop="zrqd">
                    <el-input v-model="ruleForm.zrqd" :rows="3" type="textarea" style="width: 646px;">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="考核办法:" prop="khbf">
                    <el-input v-model="ruleForm.khbf" :rows="3" type="textarea" style="width: 646px;">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="责任兑现:" prop="zrdx">
                    <el-input v-model="ruleForm.zrdx" :rows="3" type="textarea" style="width: 646px;">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="其它事项:" prop="qt">
                    <el-input v-model="ruleForm.qt" :rows="3" type="textarea" style="width: 646px;">
                    </el-input>
                  </el-form-item>
                </template>

                <MOSTY.Assort v-if="ruleForm.user.length > 1" title="独立设置人员" />
                <el-checkbox-group v-if="ruleForm.user.length > 1" class="user-check-list" v-model="signUserArr"
                  @change="changeTypeCheckedList">
                  <el-checkbox class="user-check-item" v-for="item in ruleForm.user" :key="item.id" :label="item.id"
                    :value="item.id">{{
                      item.userName }}</el-checkbox>
                </el-checkbox-group>
                <div v-if="ruleForm.chooseUser.length">
                  <div v-for="(item, index) in ruleForm.chooseUser" :key="index">
                    <el-card style="margin-top:10px" shadow>
                      <el-form-item label="姓名:">
                        <span style="color:#333;font-size: 16px;font-weight: bolder;">{{ item.userName }}</span>
                        <!-- <el-input v-model="item.userName" readonly style="width: 350px;">
                        </el-input> -->
                      </el-form-item>
                      <br />
                      <el-form-item label="安全责任清单:" prop="zrqd">
                        <el-input v-model="item.zrqd" :rows="3" type="textarea" resize="none" style="width: 400px;">
                        </el-input>
                      </el-form-item>
                      <el-form-item label="考核办法:" prop="khbf">
                        <el-input v-model="item.khbf" :rows="3" type="textarea" resize="none" style="width: 400px;">
                        </el-input>
                      </el-form-item>
                      <el-form-item label="责任兑现:" prop="zrdx">
                        <el-input v-model="item.zrdx" :rows="3" type="textarea" resize="none" style="width: 400px;">
                        </el-input>
                      </el-form-item>
                      <el-form-item label="其它事项:" prop="qt">
                        <el-input v-model="item.qt" :rows="3" type="textarea" resize="none" style="width: 400px;">
                        </el-input>
                      </el-form-item>
                    </el-card>
                  </div>

                </div>
              </el-form>
            </div>

          </div>

        </template>
        <template #footer>
          <el-button type="primary" v-loading="loading" @click="handleSave(ruleFormRef, '0')" v-if="!props.isdisabled">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button type="primary" v-loading="loading" @click="handleSave(ruleFormRef, '1')" v-if="!props.isdisabled">
            <el-icon>
              <Position />
            </el-icon>
            <span>发起签订</span>
          </el-button>
          <el-button class="btn-clas" @click="handleClose">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </template>
      </MOSTY.FromPage>
      <messageDialog v-if="isShowMessage" :userList="resUserLise" @close="messageDialogClose" />
      <!-- 选择部门 -->
      <Choosebm :showDdld="showDept" @closezzjg="closezzjg" :deptId="dwdeptId" :searchType="searchType"
        @listdata="getDeptValues" :zzlx="zzlx" />
      <!-- 选择人员弹窗 -->
      <ChooseUser v-model="chooseUserVisible" :deptId="deptId" :Single="Single" :data="memberList" :zzlx="zzlx"
        :leaderid="leaderid" @choosedUsers="choosedUsers" :key='keys'></ChooseUser>
      <!-- 预览 -->
      <div v-if="dialogVisible" class="dialog-box">
        <Kkfile :files="ruleForm.files" @changedialog="changedialog" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, reactive, watch, getCurrentInstance } from "vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { getFile } from "@/utils/getFile.js";
import * as MOSTY from "@/components/MyComponents/index";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import { getItem } from "@/utils/storage";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import Kkfile from "@/components/MyComponents/kkfile/index.vue";
import messageDialog from "./messageDialog.vue";
const showDept = ref(false);
const { proxy } = getCurrentInstance();
//新增保存按钮截流
const loading = ref(false);
const bisab = ref(false)
const Single = ref(true);
const dialogVisible = ref(false);
const ruleFormRef = ref();
const leaderid = ref("");
const searchType = ref("02");
const zzlx = ref("");
const chooseUserVisible = ref(false);
const ISbj = ref(false);
const deptId = ref(null)
const dwdeptId = ref(null)
const keys = ref(0)
const isdisabled = ref(false);
const signUserArr = ref([])
const zslxlist = ref([
  { value: "01", label: "单位对单位" },
  { value: "02", label: "单位对部门" },
  { value: "03", label: "部门对个人" },
  { value: "04", label: "主管领导对分管领导" }
]);
const emits = defineEmits(["ok"]);
//表单数据
const ruleForm = ref({
  /** 签订人(所有)*/
  user: [],
  /** 单独设置的人(部分选中的人) */
  chooseUser: [],
}
);
const isShowMessage = ref(false)
/** 失败或成功的结果 */
const resUserLise = ref([])
const fqText = ref('发起单位')
const bqdText = ref('被签订单位')


const memberList = ref([]); //成员选择的id回显
//规则校验
const rules = reactive({
  zrsmc: [{ required: true, message: "责任书名称不能为空", trigger: "blur" }],
  lxs: [{ required: true, message: "责任书类型不能为空", trigger: "blur" }],
  ryxm: [{ required: true, message: "签订人不能为空", trigger: "blur" }],
  fqxgsmc: [{ trigger: "change", required: true, message: "发起单位不能为空" }],
  rydwid: [{ trigger: "change", required: true, message: "被签订单位不能为空" }],
  qdnr: [{ trigger: "blur", required: true, message: "签订内容不能为空" }],
  mbzb: [{ trigger: "blur", required: true, message: "目标指标不能为空" }],
  rw: [{ trigger: "blur", required: true, message: "年度重点工作任务不能为空" }],
  zrqd: [{ trigger: "blur", required: true, message: "安全责任清单不能为空" }],
  khbf: [{ trigger: "blur", required: true, message: "考核办法不能为空" }],
  zrdx: [{ trigger: "blur", required: true, message: "责任兑现不能为空" }],
  qt: [{ trigger: "blur", required: true, message: "其它事项不能为空" }]
});
const props = defineProps({
  rowdata: {
    type: Object,
    default: {}
  },
  title: String,

});
// 初始化
onMounted(() => {
  resetfrom()
  ISbj.value = false
  ruleForm.value.signtype = '1'
  let dept = getItem("deptId");
  if (dept.orgBizType == "04") {
    if (dept.orgLevel.substring(0, 1) == '1' || dept.orgLevel.substring(0, 1) == '2') {
      ruleForm.value.lxs = "01";
    } else if (dept.orgLevel.substring(0, 1) == '3') {
      ruleForm.value.lxs = "02";
      zslxlist.value.splice(0, 1);
    } else {
      ruleForm.value.lxs = "03";
      zslxlist.value.splice(0, 2);
    }
  } else {
    ruleForm.value.lxs = "03";
    zslxlist.value.splice(0, 2);

  }
  if (props.xqId) {
    ISbj.value = true
    // zrsXqData(props.xqId)
  } else {
    ISbj.value = false
    changeLxs()
  }
});

/** 清除签订人,和独立设置的人 */
const clearUser = () => {
  ruleForm.value.user = []
  ruleForm.value.chooseUser = []
  ruleForm.value.ryxm = '';
}
// 切换责任书类型
const changeLxs = async (val) => {
  bisab.value = false
  clearUser()
  let dept = getItem("deptId");
  let orgLevel = dept.orgLevel.substring(0, 1);
  dwdeptId.value = null
  searchType.value = null
  ruleForm.value.rydwid = '';
  ruleForm.value.rydwmc = '';
  ruleForm.value.ryid = null
  ruleForm.value.ryxm = null
  // 单位对单位
  if (ruleForm.value.lxs == '01') {
    dwdeptId.value = null
    if (orgLevel == '1') {
      searchType.value = "02";
    } else if (orgLevel == '2') {
      searchType.value = "03";
    }
    fqText.value = '发起单位'
    bqdText.value = '被签订单位'
    ruleForm.value.fqdwid = dept.ssdwid
    ruleForm.value.fqdwmc = dept.ssdwmc
    // 查询发起单位领导
    let ry = await getRy(ruleForm.value.fqdwid, null)
    ruleForm.value.ldid = ry.fqdwid
    ruleForm.value.ldxm = ry.fqdwname
    // timelist.value[1].czrname = ruleForm.value.ldxm
  }
  if (ruleForm.value.lxs == '02') {
    searchType.value = "01";
    fqText.value = '发起单位'
    bqdText.value = '签订部门'
    dwdeptId.value = dept.ssdwid
    ruleForm.value.fqdwid = dept.ssdwid
    ruleForm.value.fqdwmc = dept.ssdwmc
    let ry = await getRy(ruleForm.value.fqdwid, null)
    ruleForm.value.ldid = ry.fqdwid
    ruleForm.value.ldxm = ry.fqdwname
    // timelist.value[1].czrname = ruleForm.value.ldxm
  }
  if (ruleForm.value.lxs == "03") {
    fqText.value = '发起部门'
    bqdText.value = '签订部门'
    searchType.value = "01";
    bisab.value = true
    dwdeptId.value = dept.ssdwid
    ruleForm.value.fqdwid = dept.ssbmid
    ruleForm.value.fqdwmc = dept.ssbmmc
    ruleForm.value.rydwid = dept.ssbmid
    ruleForm.value.rydwmc = dept.ssbmmc
    let ry = await getRy(ruleForm.value.fqdwid, null)
    ruleForm.value.ldid = ry.fqdwid
    ruleForm.value.ldxm = ry.fqdwname
    let rys = await getRy(null, ruleForm.value.rydwid)
    ruleForm.value.ryid = rys.ryid
    // ruleForm.value.ryxm = rys.ryxm
    // timelist.value[1].czrname = ruleForm.value.ldxm
  }
  // 主管领导 对 分管领导
  if (ruleForm.value.lxs == "04") {
    fqText.value = '发起单位'
    bqdText.value = '签订单位'
    searchType.value = '03'
    bisab.value = true
    dwdeptId.value = dept.ssdwid
    ruleForm.value.fqdwid = dept.ssdwid
    ruleForm.value.fqdwmc = dept.ssdwmc
    ruleForm.value.rydwid = dept.ssdwid
    ruleForm.value.rydwmc = dept.ssdwmc
    let ry = await getRy(ruleForm.value.rydwid, ruleForm.value.rydwid)
    ruleForm.value.ldid = ry.fqdwid
    ruleForm.value.ldxm = ry.fqdwname
    ruleForm.value.ryid = ry.bqddwid
    // ruleForm.value.ryxm = ry.bqddwname
    // timelist.value[1].czrname = ruleForm.value.ldxm
  }
}
// 查询审核人员活被签订人员
const getRy = async (fqdwid, bqddwbmid) => {
  let data = {
    zrslx: ruleForm.value.lxs,
    fqdwid: fqdwid,
    bqddwbmid: bqddwbmid
  }
  return new Promise(ok => {
    getApi(data, '/mosty-jcgl/securitychild/getFgldByZrslx').then((res) => {
      ok(res)
    })
  })
}

//重置
function resetfrom() {
  isdisabled.value = false;
  ruleForm.value = {}
  ruleFormRef.value.clearValidate();
  ruleFormRef.value.resetFields()
  ruleForm.value.fqxgsmc = getItem("deptId").ssdwmc;
  ruleForm.value.fqsgsid = getItem("deptId").ssdwid;
}
//关闭预览
function changedialog() {
  dialogVisible.value = false;
  UE.getEditor('editor').setShow()
}

const changeTypeCheckedList = () => {
  ruleForm.value.chooseUser = []
  let user = ruleForm.value.user
  ruleForm.value.chooseUser = signUserArr.value.map(userId => {
    return user.find(item2 => item2.id == userId)
  })

}


//选择部门
function ChooesDdld() {
  showDept.value = true;
}
//获取部门信息
const getDeptValues = async (val) => {
  clearUser()
  ruleForm.value.rydwid = val.id;
  ruleForm.value.rydwmc = val.orgName;
  deptId.value = val.id;
  if (ruleForm.value.lxs == '02') {
    let ry = await getRy(null, ruleForm.value.rydwid)
    // ruleForm.value.ryid = ry.bqddwid
    // ruleForm.value.ryxm = ry.bqddwname
    let ld = await getRy(ruleForm.value.rydwid, null)
    ruleForm.value.ldid = ld.fqdwid
    ruleForm.value.ldxm = ld.fqdwname
    // timelist.value[2].czrname = ruleForm.value.ryxm
  } else {
    let ry = await getRy(null, ruleForm.value.rydwid)
    // ruleForm.value.ryid = ry.bqddwid
    // ruleForm.value.ryxm = ry.bqddwname
    // timelist.value[2].czrname = ry.bqddwname
  }

}
//关闭弹窗
const closezzjg = (val) => {
  showDept.value = val;
};
const messageDialogClose = ()=> {
  isShowMessage.value = false
  emits('ok', false) // 退出
}
// 选择人员
function inputClick(val) {
  zzlx.value = val;
  deptId.value = null
  leaderid.value = null
  // 签订人
  if (val == "01") {
    Single.value = false
    deptId.value = ruleForm.value.rydwid
    // leaderid.value = ruleForm.value.ryid ? ruleForm.value.ryid : null;
    chooseUserVisible.value = true;
    // 审批领导
  } else if (val == "02") {
    Single.value = true
    deptId.value = ruleForm.value.fqsgsid
    leaderid.value = ruleForm.value.ldid ? ruleForm.value.ldid : null;
    chooseUserVisible.value = true;
  }
}
//人员选择
const choosedUsers = (value) => {
  

  if (zzlx.value == "01") {
    clearUser()
    ruleForm.value.ryxm = value.map(item => item.userName).toString();
    
    ruleForm.value.ryid = value.map(item => item.id);
    ruleForm.value.user = value.map(item => ({ ...item }));
  } else if (zzlx.value == "02") {
    ruleForm.value.ldxm = value[0].userName;
    ruleForm.value.ldid = value[0].id;
  }
};
// 关闭
const handleClose = () => {
  if (!props.isdisabled) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        ISbj.value = false
        ruleForm.value = {}
        ruleFormRef.value.resetFields()
        emits("ok", false);
      })
      .catch(() => {
        // catch error
      })
  } else {
    ISbj.value = false
    ruleForm.value = {}
    ruleFormRef.value.resetFields()
    emits("ok", false);
  }

};
/** 校验单独选择的人员 */
const validateChooseUserForm = () => {
  const choosedUsers = ruleForm.value.chooseUser
  // if(!choosedUsers.length) return true
  return choosedUsers.every(item => {
     const isHad = item.zrqd && item.khbf && item.zrdx && item.qt
     if(!isHad) ElMessage.error(`签订人 ${item.userName} 信息不完整`)
     return isHad
  })
}
/** 获取选择的人员对象,方便取值 */
const getChooseUserObj = () => {
  let obj = {}
  let chooseUser = ruleForm.value.chooseUser
  chooseUser.forEach(item => {
    obj[item.id] = item
  })
  return obj
}
// 保存
const handleSave = async (formEl, val) => {
  if (!formEl) return
  if(!validateChooseUserForm())return
  await formEl.validate((valid) => {
    if (valid) {
      ruleForm.value.zrslx = ruleForm.value.lxs
      ruleForm.value.xfzt = val
      const chooseUserObj = getChooseUserObj()
      /** 单独签订的人员 */
      const subsetDtos = ruleForm.value.user.map(item => {
        return {
          ryid: item.id,
          ryxm: item.userName,
          fqdwid: ruleForm.value.fqdwid,
          fqdwmc: ruleForm.value.fqdwmc,
          rydwid: item.ssdwid,
          rydwmc: item.ssdwmc,
          ldid: ruleForm.value.ldid,
          ldxm: ruleForm.value.ldxm,
          zrqd: chooseUserObj[item.id]?.zrqd || null, //	安全责任清单,
          khbf: chooseUserObj[item.id]?.khbf || null,//	考核办法,
          zrdx: chooseUserObj[item.id]?.zrdx || null,//	责任兑现,
          qt: chooseUserObj[item.id]?.qt || null,//	其他事项,
        }
      })
      const params = {
        ...ruleForm.value,
        subsetDtos: subsetDtos
      }
      delete params.user;
      delete params.chooseUser;
      loading.value = true;
      postApi(params, "/mosty-jcgl/zrs/addZrsBatch").then((res) => {
        loading.value = false;
        ElMessage.success("新增成功");
        resUserLise.value = Array.isArray(res)? res : []
        isShowMessage.value = true
        // emits("ok", false);
        // ISbj.value = false
        // ruleForm.value = {}
        // ruleFormRef.value.resetFields()
      }).catch(() => {
        loading.value = false;
      })

    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  })
}
</script>
<style lang="scss" scoped>
.top-btn {
  margin: 10px;
}

.btn-clas {
  padding: 10px 25px;
}

.config {
  height: 83vh;
  background-color: #fff;
  padding: 20px;
}

.box-big {
  width: 1400px;
  margin: 0 auto;
  display: flex;
  padding: 20px;
  height: 71vh;
}

.box-left {
  //width: 65%;
  //border-right: 1px solid var(--el-color-primary);
  overflow-y: auto;
}

.box_right {
  width: 35%;
  height: 65vh;
  overflow-y: auto;
  padding: 20px;
}

.top-word {
  display: flex;
  justify-content: space-between;
}

.word-box {
  width: 1021px;
  background-color: #f0f3f4;
}

::v-deep .el-radio.is-bordered.is-checked {
  background-color: var(--el-color-primary) !important;
  color: #fff !important;
}

::v-deep .el-radio__input.is-checked+.el-radio__label {
  color: #fff !important;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #fff !important;
}

.time-top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.name-box {
  font-family: Microsoft YaHei, Microsoft YaHei;
  font-weight: bold;
  font-size: 14px;
  color: #191919;
}

.lable-time {
  display: inline-block;
  padding: 0px 10px;
  border-radius: 2px 2px 2px 2px;
  color: #fff;
  margin: 0px 10px;
}

.gren {
  background: #07877e;
}

.reds {
  background-color: #e91717;
}

.yess {
  background: #ebd0a1;
}

.time-ri {
  font-family: Microsoft YaHei, Microsoft YaHei;
  font-weight: 400;
  font-size: 14px;
  color: #191919;
}

.ldxm {
  font-weight: 400;
  font-size: 12px;
  margin: 10px;
}

::v-deep .el-card {
  background: #f0f3f4 !important;
  border-radius: 2px 2px 2px 2px !important;
}

::v-deep .edui-default .edui-editor-toolbarbox {
  position: none !important;
}
</style>
<style lang="scss">
.bg_color {
  background: #fff !important;
}

.input_div {
  width: 646px;
  color: #131313;
  background-color: #d3dbdd;
  line-height: 1.5;
  font-size: 14px !important;
  border: 1px solid var(--el-color-primary);
  min-height: 115px;
  border-radius: 4px;
  padding: 5px 15px;

  div,
  span,
  font,
  p {
    font-size: 14px !important;
    line-height: 1.5 !important;
    text-indent: 0 !important;
  }
}

.user-check-list {
  ::v-deep .el-checkbox__label {
    color: #000;
  }

  .user-check-item {
    color: #000;
  }
}
</style>
