<template>
  <div>
    <div class="bigBox">
      <MOSTY.FromPage v-loading="loadingForm" :title="props.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="zrslx" style='width:100%;'>
                  <el-radio-group v-model="ruleForm.zrslx" size="small" @change="changeLxs">
                    <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="责任书模板类型:" prop="zrsmodellx" style='width:100%;'>
                  <el-cascader v-model="ruleForm.zrsmodellx" :options="specialDangerOpts" :props="cascaderProps"
                    clearable @change="changeZrs" />
                </el-form-item>
                <el-form-item label="序言:">
                  <el-input v-model="ruleForm.preface" :rows="10" type="textarea" style="width: 646px;">
                  </el-input>
                </el-form-item>
                <el-form-item label="目标指标:">
                  <el-input v-model="ruleForm.mbzb" :rows="10" type="textarea" style="width: 646px;">
                  </el-input>
                </el-form-item>
                <el-form-item label="年度重点工作任务:">
                  <el-input v-model="ruleForm.rw" :rows="10" type="textarea" style="width: 646px;">
                  </el-input>
                </el-form-item>
                <el-form-item label="安全职责:">
                  <el-input v-model="ruleForm.zrqd" :rows="10" type="textarea" style="width: 646px;">
                  </el-input>
                </el-form-item>
                <el-form-item label="考核办法:">
                  <el-input v-model="ruleForm.khbf" :rows="10" type="textarea" style="width: 646px;">
                  </el-input>
                </el-form-item>
                <el-form-item label="责任兑现:">
                  <el-input v-model="ruleForm.zrdx" :rows="10" type="textarea" style="width: 646px;">
                  </el-input>
                </el-form-item>
                <el-form-item label="其它事项:">
                  <el-input v-model="ruleForm.qt" :rows="10" type="textarea" style="width: 646px;">
                  </el-input>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </template>
        <template #footer>
          <el-button type="primary" v-loading="loading" @click="handleSave(ruleFormRef)">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>{{ isAdd ? '保存修改' : '新增保存' }}</span>
          </el-button>
          <el-button class="btn-clas" @click="handleClose">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </template>
      </MOSTY.FromPage>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, reactive, computed, getCurrentInstance, onUnmounted } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
//新增保存按钮截流
const loading = ref(false);
const loadingForm = ref(false);
const zslxlist = ref([
  { value: "01", label: "单位对单位" },
  { value: "02", label: "班子成员对分管部门负责人" },
  { value: "03", label: "部门负责人对部门员工" },
  { value: "04", label: "主要领导对班子成员" },
]);
const isAdd = ref(false)
const emits = defineEmits(["changeAddVi"]);
//表单数据
const ruleForm = ref({
  id: '',
  zrslx: '01',
  zrsmodellx: ['0101', '010101'],
  mbzb: '',
  preface: '',
  rw: '',
  zrqd: '',
  khbf: '',
  zrdx: '',
  qt: '',
});
const ruleFormRef = ref();
//规则校验
const rules = reactive({
  zrslx: [{ required: true, message: "责任书类型不能为空", trigger: "change" }],
  zrsmodellx: [{ required: true, message: "层级不能为空", trigger: "change" }],
  fqxgsmc: [{ trigger: "change", required: true, message: "发起单位不能为空" }],
  rydwid: [{ trigger: "change", required: true, message: "被签订单位不能为空" }],
  qdnr: [{ trigger: "change", required: true, message: "签订内容不能为空" }],
  mbzb: [{ trigger: "change", required: true, message: "目标指标不能为空" }],
  rw: [{ trigger: "change", required: true, message: "年度重点工作任务不能为空" }],
  // zrqd: [{ trigger: "change", required: true, message: "安全责任清单不能为空" }],
  // khbf: [{ trigger: "change", required: true, message: "考核办法不能为空" }],
  // zrdx: [{ trigger: "change", required: true, message: "责任兑现不能为空" }],
  // qt: [{ trigger: "change", required: true, message: "其它事项不能为空" }]
});
const props = defineProps({
  title: String,
});
const cascaderProps = ref({
  value: 'value',
  label: 'label',
  children: 'children',
  emitPath: false
})
// 重置表单函数
const resetForm = () => {
  ruleForm.value = {
    id: '',
    zrslx: '01',
    zrsmodellx: ['0101', '010101'],
    mbzb: '',
    preface: '',
    rw: '',
    zrqd: '',
    khbf: '',
    zrdx: '',
    qt: '',
  }
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }
}
// 初始化
onMounted(() => {
  resetForm()
  getDicTree("D_TB_ZRS_MODEL_LX").then(res => {
    specialDangerOptsData.value = res
    specialDangerOpts.value = specialDangerOptsData?.value[0].children
    getData('010101')
  })
});
const specialDangerOptsData = ref([])
const specialDangerOpts = ref([])
/** 获取字典树 */
const getDicTree = (zdbh) => {
  return new Promise((resolve, reject) => {
    getApi({ zdbh: zdbh, }, "/mosty-base/sysDict/getDictTree").then(res => {
      const toNeedArr = (arr) => {
        if (!Array.isArray(arr)) return []
        return arr.map(item => {
          return {
            label: item.zdmc,
            value: item.dm,
            children: toNeedArr(item.itemList)
          }
        })
      }
      const treeArr = toNeedArr(res.itemList)
      resolve(treeArr)
    })
  })
}
const changeZrs = (data) => {
  getData(data)
}
const getData = (data) => {
  loadingForm.value = true
  getApi({ zrsmodellx: data }, "/mosty-jcgl/zrsModel/getZrsModel")
    .then((res) => {
      if (res) {
        ruleForm.value.id = res.id
        ruleForm.value.preface = res.preface
        ruleForm.value.mbzb = res.mbzb
        ruleForm.value.rw = res.rw
        ruleForm.value.zrqd = res.zrqd
        ruleForm.value.khbf = res.khbf
        ruleForm.value.zrdx = res.zrdx
        ruleForm.value.qt = res.qt
        isAdd.value = true
      } else {
        ruleForm.value.id = ''
        ruleForm.value.preface = ''
        ruleForm.value.mbzb = ''
        ruleForm.value.rw = ''
        ruleForm.value.zrqd = ''
        ruleForm.value.khbf = ''
        ruleForm.value.zrdx = ''
        ruleForm.value.qt = ''
        isAdd.value = false
      }
      loadingForm.value = false
    }).catch(() => {
      loadingForm.value = false
      console.error("获取数据失败")
    })
}
const changeLxs = (data) => {
  // 根据类型找到对应的索引
  const index = zslxlist.value.findIndex(item => item.value === data)
  if (index > -1 && specialDangerOptsData.value[index]) {
    specialDangerOpts.value = specialDangerOptsData.value[index].children || []
    ruleForm.value = {
      zrslx: ruleForm.value.zrslx,
      zrsmodellx: '',
      mbzb: '',
      preface: '',
      rw: '',
      zrqd: '',
      khbf: '',
      zrdx: '',
      qt: '',
    }
  }
}

// 关闭
const handleClose = () => {
  if (!props.isdisabled) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        resetForm()
        emits("changeAddVi", false);
      })
      .catch(() => {
        // catch error
      })
  } else {
    resetForm()
    emits("changeAddVi", false);
  }
};

// 保存
const handleSave = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      loading.value = true;
      const formData = {
        ...ruleForm.value,
      }
      if (Array.isArray(ruleForm.value.zrsmodellx)) {
        formData.zrsmodellx = formData.zrsmodellx[formData.zrsmodellx.length - 1]
      }
      const apiUrl = isAdd.value
        ? "/mosty-jcgl/zrsModel/editZrsModel"
        : "/mosty-jcgl/zrsModel/addZrsModel"
      postApi(formData, apiUrl).then(() => {
        loading.value = false;
        ElMessage.success(isAdd.value ? "修改成功" : "新增成功");
        // 重新获取数据更新状态
        getData(formData.zrsmodellx)
        // emits("changeAddVi", false);
      }).catch(() => {
        loading.value = false;
      })
    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  })
}
// 在组件卸载时清理
onUnmounted(() => {
  resetForm()
})
</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;
  }
}
</style>