<template>
  <div>
    <MOSTY.FromPage :title="props.title" @closeDialog="handleClose">
      <template #content>
        <MOSTY.Assort :title="'检查配置信息'" />
        <div class='config'>
          <el-form ref="fromsRef" :model="ruleForm" :rules="rules" label-width="120px" :disabled="!savebtn"
            class="demo-ruleForm.value">
            <el-form-item label="检查标题" prop="title">
              <el-input placeholder="请输入检查标题" v-model="ruleForm.title" clearable style="width: 100%"></el-input>
            </el-form-item>
            <el-form-item label="发起检查单位" prop="orgid" v-if="props.title == '新增检查配置'">
              <el-input v-model="ruleForm.orgid" clearable style="width: 100%" disabled></el-input>
            </el-form-item>
            <el-form-item label="发起检查单位" prop="deptname" v-if="props.title != '新增检查配置'">

              <el-input v-model="ruleForm.deptname" clearable style="width: 100%" disabled></el-input>
            </el-form-item>
            <el-form-item label="检查类型" prop="half">
              <el-select v-model="ruleForm.half" clearable placeholder="请选择检查类型">
                <el-option v-for="item in D_TB_FQJCLX" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="ruleForm.startTime" type="date" label="开始时间" format="YYYY-MM-DD" clearable
                value-format="YYYY-MM-DD" placeholder="请选择开始时间" style="width: 100%" @change="ruleForm.endTime = ''" />
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker v-model="ruleForm.endTime" type="date" label="结束时间" value-format="YYYY-MM-DD" clearable
                format="YYYY-MM-DD" placeholder="请选择结束时间" style="width: 100%" :disabled-date="disabledjsrq" />
            </el-form-item>
            <!-- (需要进行基础检查的才需要选择) -->
            <!-- <el-form-item label="基础检查模板" prop="tname">
              <el-input v-model="ruleForm.tname" readonly placeholder="请选择基础检查模板" @click="showJcjcmb = true" />
              <span>(需要进行基础检查的才需要选择)</span>
            </el-form-item> -->
            <el-form-item label="检查方式" prop="checkType">
              <el-radio-group v-model="ruleForm.checkType">
                <el-radio label="1">常规检查</el-radio>
                <el-radio label="2">暗查暗访</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="checkPlan" v-if="ruleForm.checkType == 2" label="检查方案">
              <MOSTY.Upload :limit="1" :widthNumber="732" :showinput="true"
                :placeholder="'请上传检查方案（pdf,ofd,doc,docx,xls,xlsx）'"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx']" :nopicer="true" :isImg="false"
                :ShowfileList="true" v-model="ruleForm.checkPlan" :delrow="delrow">
              </MOSTY.Upload>
            </el-form-item>
            <el-form-item label="检查内容" prop="content" style="width: 100%">
              <el-input v-model="ruleForm.content" type="textarea" />
            </el-form-item>
          </el-form>
        </div>
        <MOSTY.Assort :title="'检查小组信息'" />
        <el-button type="primary" @click="addjcxzclick" v-if="savebtn">
          <el-icon>
            <CirclePlus />
          </el-icon>
          <span>添加（必填）</span>
        </el-button>
        <div class="tabBox">
          <el-table :row-class-name="rowDataIndex" ref="multipleTableRef" :data="ruleForm.jczList" stripe
            style="width: 100%" @selection-change="handleSelectionChange" border>
            <el-table-column label="带队领导" property="leadername"></el-table-column>
            <el-table-column label="检查组长" property="zzxm"></el-table-column>
            <el-table-column label="检查成员">
              <template #default="{ row }">
                <span v-for="item in row.userList" :key="item">
                  {{ item.userName }}、</span>
              </template>
            </el-table-column>
            <el-table-column label="检查范围" property="taskListName">
            </el-table-column>
            <el-table-column label="操作" v-if="savebtn">
              <template #default="scope">
                <span class="operate" @click="handleGzs(scope.row, scope.$index)" style="
                        color: rgb(10, 104, 228);
                        text-decoration: underline;">编辑</span>
                <span class="operate" @click="deleteGzs(scope.$index)" style="
                        color: rgb(10, 104, 228);
                        text-decoration: underline;
                      ">删除</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <MOSTY.Assort :title="'附件'" />
        <div>
          <el-form :model="ruleForm" label-width="120px" class="demo-dynamic">
            <el-form-item label="附件">
              <MOSTY.Upload :widthNumber="500" :limit="5" :nopicer="true" :isImg="false" :ShowfileList="true"
                v-model="ruleForm.file" :showinput="true" :delrow="delrow" :disabled="!savebtn" :isEdit="fileEdit">
              </MOSTY.Upload>
            </el-form-item>
          </el-form>
        </div>
        <div class="tabsbox">
          <div class="header">
            <div class="bottom">
              <el-tabs class="yhzlbox" type="card" v-model="activeTab" @tab-click="onTabClick">
                <el-tab-pane :label="item.label" :name="item.value" v-for="(item, i) in tabs" :key="i" />
              </el-tabs>
            </div>
          </div>
        </div>
        <MOSTY.Assort :title="'检查内容配置'" />
        <!-- <el-table ref="multipleTableRef" stripe :data="ruleForm.jcjcmbList" height='32vh' style="width: 100%"
          @selection-change="handleSelectionChange" border>
          <el-table-column property="orgname" label="单位" show-overflow-tooltip />
          <el-table-column property="objname" label="风险单元" show-overflow-tooltip />
          <el-table-column label="风险等级" property="risklevel">
            <template #default="{ row }">
              <span v-if="row.risklevel == '4'" class="fxdjspan reds">重大风险</span>
              <span v-else-if="row.risklevel == '3'" class="fxdjspan orgs">较大风险</span>
              <span v-else-if="row.risklevel == '2'" class="fxdjspan blus">一般风险</span>
              <span v-else-if="row.risklevel == '1'" class="fxdjspan gres">低风险</span>
              <span v-else>待定</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="listQuery" @changeNo="handleCurrentChange2" @changeSize="handleSizeChange2" />
        </div> -->
        <component :is="currentCom" :title="title" :data="ruleForm.inspectionContentList" :activeTab="activeTab" :disabled="!savebtn"
          @ndzdxmlist=getinspectionContentList @deletelist="deletenspectionContentList" />
      </template>
      <template #footer>
        <el-button type="primary" v-if="savebtn" :loading="loading" @click="handleSave(fromsRef)">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span>
        </el-button>
        <el-button @click="handleClose" type="primary">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span>
        </el-button>
      </template>

    </MOSTY.FromPage>

    <!-- 检查小组信息 start -->
    <Addjcxzxz :addShow="addShow" @changeclose="changeclose" :fromObj="fromObj" :jczList="ruleForm.jczList"
      :editIndex="editIndex" @getList="getListEvent" />

    <!-- 基础检查模板 -->
    <!-- <Jcjcmb v-model="showJcjcmb" v-if="showJcjcmb" @confirm="onClickConfirmMb" /> -->
  </div>
</template>
<script setup>
// 引入
import {
  ref,
  onMounted,
  defineProps,
  defineEmits,
  reactive,
  watch,
  getCurrentInstance,
  defineAsyncComponent
} from "vue";
import Jcjcmb from "@/views/fxgk/components/Dialog/Jcjcmb.vue"
import { getItem } from "@/utils/storage";
import * as MOSTY from "@/components/MyComponents/index";
import { getErrMsg } from '@/utils/tools.js'
import Addjcxzxz from "./Addjcxzxz.vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();
const { D_TB_FQJCLX } = proxy.$dict("D_TB_FQJCLX");
const loading = ref(false); //新增保存按钮截流
const fromsRef = ref()
//规则校验
const rules = reactive({
  title: [{ required: true, message: "检查标题不能为空", trigger: "blur" }],
  half: [{ required: true, message: "检查类型不能为空", trigger: "blur" }],
  orgid: [{ trigger: "blur", required: true, message: "发起检查单位不能为空" }],
  deptname: [{ trigger: "blur", required: true, message: "发起检查单位不能为空" }],
  // tname: [{ trigger: "change", required: true, message: "基础检查模板不能为空" }],
  startTime: [{ trigger: "blur", required: true, message: "请选择开始时间" }],
  endTime: [{ trigger: "blur", required: true, message: "结束时间不能为空" }],
  checkType: [{ trigger: "blur", required: true, message: "检查方式不能为空" }],
  checkPlan: [{ trigger: "blur", required: true, message: "请用户上传检查方案" }],
});
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  xqId: {
    type: String,
    default: ''
  },
});
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  total: 0
})
const addShow = ref(false);
const fromObj = ref({}); //检查小组编辑
const savebtn = ref(true)
// const showJcjcmb = ref(false)
const emits = defineEmits(["changeAddVi", "changeclose"]);
const tabs = [
  {
    label: "年度重点工作任务",
    value: "ndzdxm",
    index: '0'
  },
  {
    label: "专项检查内容",
    value: "zxjcnr",
    index: '1'
  },
];
const title = ref("年度重点工作任务");
const activeTab = ref("ndzdxm"); //默认选中
const currentCom = ref("ndzdxm"); //动态组件
const onTabClick = (e) => {
  const tabName = e.props.name;
  activeTab.value = tabName;
  currentCom.value = defineAsyncComponent(() => import(`./components/${e.props.name}.vue`))
  title.value = tabs.find((item) => item.value === e.props.name).label;
}

//表单数据
const ruleForm = ref({
  title: "",
  orgid: getItem("deptId").ssbmmc, //发起检查部门ID
  half: "", //发起检查单位ID
  startTime: new Date(),
  endTime: new Date(), //检查结束时间
  mbid: "", //基础检查模板
  content: "", //	检查考评内容
  file: null, //检查附件（检查相关文件）id
  jczList: [], //检查组list
  jcjcmbList: [], //排查项
  inspectionContentList: [], //检查内容
  checkType: "1", //检查方式
  checkPlan: null, //检查方案
});
const rowDataIndex = (row, rowIndex) => {
  // 给每行增加index参数，值为下标
  row.index = rowIndex + 1;
};
function disabledjsrq (time) {
  return time.getTime() + 24 * 60 * 60 * 1000 < new Date(ruleForm.value.startTime).getTime()
}
// 初始化
onMounted(() => {
  currentCom.value = defineAsyncComponent(() => import(`./components/${activeTab.value}.vue`))
});
watch(
  () => props.title,
  (newValue) => {
    if (newValue == '新增检查配置') {
      ruleForm.value = {};
      ruleForm.value.orgid = getItem("deptId").ssbmmc;
    }
    if (newValue == '检查配置详情') {
      savebtn.value = false
    } else {
      savebtn.value = true
    }
  },
  { deep: true, immediate: true }
);
watch(
  () => props.xqId,
  (val) => {
    if (val) {
      getjcpzxq(props.xqId);
    }
  },
  { deep: true, immediate: true }
);
//模板选择
// const onClickConfirmMb = (val) => {
//   listQuery.value.tid = val.id
//   const { tname, id } = val
//   ruleForm.value = { ...ruleForm.value, tname, mbid: id }
//   showJcjcmb.value = false;
//   jcjcmbcq()
// }
function jcjcmbcq (val) {
  //查询基础检查模板的详情
  // getApi({ tid: val, pageCurrent: 1, pageSize: 1000 }, `/mosty-jcgl/zhjcmb/chooseList`).then((res) => {
  getApi(listQuery.value, `/mosty-jcgl/zhjcmb/getListY`).then((res) => {
    // ruleForm.value.jcjcmbList = res.records ? res.records : []
    listQuery.value.total = res.total
  }
  );
}
//
function getjcpzxq (id) {
  getApi({}, "/mosty-jcgl/zhjc/getInfo?id=" + id).then((res) => {
    if (res) {
      ruleForm.value = res;

      res.jczList.forEach((item) => {
        let username = [];
        if (item.taskDtoList != null) {
          let taskarr = [];
          for (let i = 0; i < item.taskDtoList.length; i++) {
            const el = item.taskDtoList[i];
            taskarr.push(el.orgname);
          }
          item.taskListName = taskarr
        }
        if (item.userList) {
          for (let x = 0; x < item.userList.length; x++) {
            const e = item.userList[x];
            username.push(e.userName);
          }
        }
        item.userListName = username
        listQuery.value.tid = res.mbid
        jcjcmbcq();
      });
      ruleForm.value.inspectionContentList = [...res.inspectionContentList]; //检查内容
    }
  });
}

// 检查小组信息表格数据
const editIndex = ref(false);

// 方法
//点击添加（检查小组信息）
function addjcxzclick () {
  editIndex.value = null;
  fromObj.value = {
    leaderid: '',
    zzid: '',
    taskList: [],
    userList: [],
  };
  addShow.value = true;
}
//删除小组数据
function deleteGzs (index) {
  ruleForm.value.jczList.splice(index, 1);
}
// 关闭
const handleClose = () => {
  if (savebtn.value) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emits("changeAddVi", false);
        ruleForm.value = {};
        ruleForm.value.orgid = getItem("deptId").ssbmmc;
      })
      .catch(() => {
        // catch error
      })
  } else {
    emits("changeAddVi", false);
    ruleForm.value = {};
    ruleForm.value.orgid = getItem("deptId").ssbmmc;
  }

};

// 或者子组件的数据
const getListEvent = (val) => {
  if (!ruleForm.value.jczList) {
    ruleForm.value.jczList = []
  }
  if (editIndex.value != null) {
    for (let i = 0; i < ruleForm.value.jczList.length; i++) {
      if (editIndex.value == i) {
        ruleForm.value.jczList[i] = val
      }
    }
    // ruleForm.value.jczList.forEach((item, index) => {
    //   if (editIndex.value == index) {
    //     ruleForm.value.jczList.splice(index, 1, val);
    //   }
    // });
  } else {
    ruleForm.value.jczList.push(val);
  }
};
// 年度重点工作任务数据
const getinspectionContentList = (val, editIndex) => {
  if (!ruleForm.value.inspectionContentList) {
    ruleForm.value.inspectionContentList = []
  }
  // 使用id查找现有数据的下标
  if (val.id) {
    const existingIndex = ruleForm.value.inspectionContentList.findIndex(item => item.id === val.id);
    if (existingIndex !== -1) {
      Object.assign(ruleForm.value.inspectionContentList[existingIndex], val);
    } else {
      // 没有找到相同id，作为新数据添加
      ruleForm.value.inspectionContentList.push(val);
    }
  } else {
    // 如果没有id，作为新数据添加（新增情况）
    ruleForm.value.inspectionContentList.push(val);
  }

};
//删除年度重点工作任务数据
function deletenspectionContentList (row) {
  const index = ruleForm.value.inspectionContentList.findIndex(item => item.id === row.id);
  ruleForm.value.inspectionContentList.splice(index, 1);
  // for (let i = 0; i < ruleForm.value.inspectionContentList.length; i++) {
  //   if (editIndex == i) {
  //     ruleForm.value.inspectionContentList[i] = val
  //   }
  // }
}
// 保存
const handleSave = async (fromsRef) => {
  if (!fromsRef) return;
  await fromsRef.validate((valid, fields) => {
    if (valid) {
      if (ruleForm.value) {
        if (ruleForm.value.file || ruleForm.value.checkPlan) {
          ruleForm.value.file = ruleForm.value.file ? ruleForm.value.file.toString() : null;
          ruleForm.value.checkPlan = ruleForm.value.checkPlan ? ruleForm.value.checkPlan.toString('') : null;
        }
        loading.value = true;
        if (props.title == "新增检查配置") {
          postApi(ruleForm.value, "/mosty-jcgl/zhjc/addZhjc")
            .then((res) => {
              loading.value = false;
              ElMessage.success("新增成功");
              emits("changeAddVi", false);
              ruleForm.value = {};
              ruleForm.value.orgid = getItem("deptId").ssbmmc;
            })
            .catch((err) => {
              loading.value = false;
            });
        } else if (props.title == "修改检查配置") {
          postApi(ruleForm.value, "/mosty-jcgl/zhjc/updateZhjc").then(() => {
            loading.value = false;
            ElMessage.success("修改成功");
            emits("changeAddVi", false);
          }).catch((err) => {
            loading.value = false;
          });
        }
      }
    } else {
      ElMessage.warning(getErrMsg(fields) || '请输入必填项！！！!')
    }
  })

};
// 编辑检查小组数据
const handleGzs = (val, index) => {
  editIndex.value = index;
  fromObj.value = val;
  addShow.value = true;
};
//关闭检查小组信息
const changeclose = () => {
  addShow.value = false;
};
//页码发生变化
const handleCurrentChange2 = (val) => {
  listQuery.value.pageCurrent = val;
  jcjcmbcq();
};
//查询条数发生变化
const handleSizeChange2 = (val) => {
  listQuery.value.pageSize = val;
  jcjcmbcq();
};

</script>

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

  .from_fix {
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    margin-top: 10px;

    .el-input {
      width: 100%;
    }
  }
}

::v-deep .el-form-item__content {
  flex-wrap: nowrap !important;
}

.config {
  width: 1251px;
  margin: auto;

  .el-form {
    padding: 10px;
    margin-top: 10px;
    flex-wrap: wrap;
    justify-content: space-between;
  }

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

  .el-input {
    width: 350px;
  }
}

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

.form>div {
  position: relative;
  margin-top: 30px;
  display: flex;
  justify-content: space-between;

  div {
    display: flex;
    align-items: center;

    .el-select {
      width: 65%;
    }
  }
}

.el-input {
  width: 75%;
}

.two .el-input {
  width: 65%;
}

.three {
  justify-content: flex-start !important;

  .el-select {
    width: 15%;
  }
}

.four {
  display: flex;
  align-items: center;

  span {
    width: 5%;
  }

  .el-textarea__inner {
    width: 95%;
  }
}

.group {
  margin-top: 50px;
  position: relative;
}

.fj {
  margin-top: 50px;
  width: 100%;

  .content {
    width: 100%;
    display: flex;
    padding: 20px;

    div {
      display: flex;
      width: 85%;
      align-items: center;
    }

    justify-content: space-between;
  }
}

.jc {
  margin-top: 50px;
}

.tabBox {
  height: 300px !important;
}

.el-table {
  height: 300px !important;
  border: 1px solid var(--el-color-primary);
}

.el-form-item__content {
  flex-wrap: nowrap;
}

.el-collapse {
  border-color: var(--el-color-primary);
  height: 460px;
}

::v-deep .el-collapse-item__header {
  border-bottom-color: var(--el-color-primary);
  color: #000 !important;
}

::v-deep .el-collapse-item__header.is-active {
  border-bottom-color: transparent;
}

.fxdjspan {
  display: inline-block !important;
  width: 100px;
  text-align: center;
  padding: 5px 0;
  border-radius: 5px;
  color: #fff !important;
}

.reds {
  background-color: #e80000;
}

.orgs {
  background-color: #ff8040;
}

.blus {
  background-color: #e2d101;
}

.gres {
  background-color: #0080ff;
}

.tabsbox {
  .header {
    margin-bottom: 0px;

    .bottom {
      padding-left: 0px;
      padding-bottom: 0px;
    }
  }
}
</style>
