<template>
  <MOSTY.PageTree :pageTitle="'风险辨识计划列表'" @getDeptId="getdeptId">
    <template #serach>
      <el-divider />
      <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
      <el-divider />
      <div class="btnBox">
        <el-button type="primary" @click="addUserHander">
          <el-icon>
            <CirclePlus />
          </el-icon>
          <span>新增</span>
        </el-button>
      </div>
    </template>
    <template #table>
      <section class="eltab9">
        <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloading" :isSelect="false"
          :isSort="true" style="width: 100%;">
          <template #bslx="{ row }">
            <dict-tag :options="D_BZ_BSLX" :value="row.bslx" :tag="false" />
          </template>
          <template #status="{ row }">
            <span v-if="row.status == '0'">辨识结束</span>
            <span v-if="row.status == '1'">未下发</span>
            <span v-if="row.status == '2'">辨识中</span>
          </template>
          <template #actions="{ row }">
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要下发吗?"
              @confirm="tabrowxiafa(row)" v-if="row.status == 1">
              <template #reference>
                <span span class="operdel" size="small"> <el-icon>
                  </el-icon>下发</span>
              </template>
            </el-popconfirm>
            <span class="operedit" @click="handlexg(row)" v-if="row.status == 1"><el-icon>
                <EditPen />
              </el-icon>修改</span>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="handledelete(row)" v-if="row.status == 1">
              <template #reference>
                <span span class="operdel" size="small"> <el-icon>
                    <Delete />
                  </el-icon>删除</span>
              </template>
            </el-popconfirm>
            <span class="operesee" @click="handleSee(row)"> <el-icon>
                <View />
              </el-icon>查看</span>
            <span class="operesee" @click="seeInfotable(row)"> <el-icon>
                <View />
              </el-icon>辨识进度</span>
          </template>
        </MOSTY.Table>
      </section>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="listQuery" @changeSize="handleSizeChange" @changeNo="handleCurrentChange">
        </MOSTY.Pages>
      </div>
    </template>
  </MOSTY.PageTree>
  <div v-if="addDiaShow" class="dialod">
    <el-dialog :title='title' v-model="addDiaShow" stripe width="900px" :before-close="handleClose">
      <!-- 培训计划新增或修改 -->
      <div class="config">
        <el-form ref="frombt" :model="ruleForm" :rules="rules" label-width="135px" class="demo-ruleForm.value"
          :disabled="!saveshow">
          <el-form-item label="策划单位：">
            <el-input v-model="ruleForm.orgName" disabled clearable style="width:250px"></el-input>
          </el-form-item>
          <el-form-item label="策划部门：">
            <el-input v-model="ruleForm.draftDepname" disabled clearable style="width:250px"></el-input>
          </el-form-item>
          <el-form-item label="辨识类型:" prop="bslx">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_BSLX" v-model="ruleForm.bslx" style="width: 725px"
              selectType="select" placeholder='请选择辨识类型' @onChange='onChangebslx' />
          </el-form-item>
          <el-form-item label="选择日期：" prop="dates">
            <el-date-picker style="width:725px" v-model="ruleForm.dates" type="daterange" :disabled-date="disabledDate"
              range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" :size="size" format="YYYY-MM-DD"
              date-format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="通知名称：" prop="identifyName">
            <el-input v-model="ruleForm.identifyName" clearable style="width:725px"></el-input>
          </el-form-item>
          <el-form-item label="评价方式:" prop="pjfs">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_PJFS" v-model="ruleForm.pjfs" style="width: 725px"
              selectType="select" placeholder='请选择评价方式' />
          </el-form-item>
          <el-form-item label="参与人员:" prop="usernames" style='display:flex;' v-if='ruleForm.bslx == "02"'>
            <el-input v-model="ruleForm.usernames" type="textarea" :rows="3" placeholder="请选择参与人员" disabled clearable
              style="width: 650px;margin-right:10px;">
            </el-input>
            <el-button class='cursor' @click="ChooesDdld('01')">选择</el-button>
          </el-form-item>
          <el-form-item label="附件上传：" style="display: flex; width: 100%">
            <div style="display: flex;">
              <MOSTY.Upload width="600px !important" :widthNumber="726" :limit="1" :nopicer="true" :isImg="false"
                :ShowfileList="true" v-model="ruleForm.files" :showinput="true"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx','wps']" :placeholder="'请上传pdf,ofd,doc,docx,xls,xlsx,wps'"
                style="width:100%"></MOSTY.Upload>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="saverk(frombt)" v-if="showrkbtn">下发</el-button>
          <el-button type="primary" v-if="saveshow" @click="handleSave(frombt)" :loading="loading">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button @click="handleClose" type="primary">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </span>
      </template>
      <!-- 选择人员 -->
      <ChooseUser v-model="chooseUserVisible" :searchType='"04"' :zzlx="zzlx" :deptId="orgcode" :Single="singleShow"
        :data="memberList" @choosedUsers="getSonValue">
      </ChooseUser>
    </el-dialog>
  </div>
  <!-- 市列表弹框 -->
  <sgsTC v-if="isShowSgs" :row="currRow" :years="listQuery.identifyYear" :title="`${currRow.identifyName}-详情`"
    @close="sgTcClose" />
  <!-- 县列表 -->
  <xgsTC v-if="isShowXgs" :row="currRow" :years="listQuery.identifyYear" :title="`${currRow.identifyName}-详情`"
    @close="xgsTcClose" />
  <!-- 其他用户 -->
  <YsPage v-if="isShowYsPage" :row="currRow" :years="listQuery.identifyYear" :title="`${currRow.identifyName}-详情`"
    @close="ysPageClose" />
</template>
<script setup>
import { reactive, getCurrentInstance, onMounted, ref, watch } from 'vue'
import { ElMessage } from "element-plus";
import { getItem } from "@/utils/storage";
import { isString } from "@/utils/tools.js"
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { filterYear, filterqx } from "@/utils/auth.js";
import * as MOSTY from "@/components/MyComponents/index";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import sgsTC from "./component/sgsTC.vue";
import xgsTC from './component/xgsTC.vue';
import YsPage from './component/YsPage.vue';
const { proxy } = getCurrentInstance();
const { D_BZ_BSLX, D_BZ_PJFS } = proxy.$dict("D_BZ_BSLX", "D_BZ_PJFS")
const addDiaShow = ref(false);
const title = ref("");//弹窗标题
const frombt = ref();
const saveshow = ref(true)
const showrkbtn = ref(true)
const singleShow = ref(false); //单选多选
const memberList = ref([]);
const zzlx = ref(null);
const chooseUserVisible = ref(false); //选择领导弹窗
const loading = ref(false); //新增保存按钮截流
const searchArr = reactive([
  {
    showType: "select",
    prop: "identifyYear",
    width: '250px',
    defaultVal: new Date().getFullYear(),
    options: filterYear(7),
  }, {
    showType: "input",
    prop: "identifyName",
    width: '250px',
    placeholder: '请输入辨识名称或策划单位名称进行查询',
  },
]);
const tableColumn = ref([
  {
    title: "辨识类型",
    prop: "bslx",
    sortable: true,
    slot: true,
  },
  {
    title: "通知名称",
    prop: "identifyName",
    sortable: true
  },
  {
    title: "策划单位",
    prop: "orgName",
    sortable: true
  },
  {
    title: "策划人",
    prop: "xtCjr",
    sortable: true
  },
  {
    title: "开始时间",
    prop: "begindate",
    sortable: true
  },
  {
    title: "截止时间",
    prop: "enddate",
    sortable: true
  },
  {
    title: "状态",
    prop: "status",
    slot: true,
    sortable: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])

const tableloading = ref(false)
const ruleForm = ref({});
//规则校验
const rules = reactive({
  dates: [{ required: true, message: "开始日期不能为空", trigger: "blur" }],
  identifyName: [{ trigger: "blur", required: true, message: "辨识名称不能为空" }],
  pjfs: [{ trigger: "blur", required: true, message: "请选择评价方式" }],
  bslx: [{ trigger: "blur", required: true, message: "请选择辨识类型" }],
  usernames: [{ trigger: "blur", required: true, message: "请选择参与人员" }],
});
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  total: 0,
  identifyYear: new Date().getFullYear(),
});
const total = ref(0);
// 表格数据
const tableData = ref([])

// 禁止选择今天以前
const disabledDate = time => {
  return time.getTime() < Date.now() - 8.64e7;
}
//查询
function onSearch(obj) {
  listQuery.value.identifyYear = obj.identifyYear
  listQuery.value.identifyName = obj.identifyName
  listQuery.value.pageCurrent = 1
  getTabList();
}
//选择右侧部门
const getdeptId = (val) => {
  listQuery.value.orgCode = val.id;
  listQuery.value.pageCurrent = 1
  getTabList();
};
//获取表格数据
function getTabList() {
  tableloading.value = true
  getApi(listQuery.value, '/mosty-jcgl/dangerPlanlist/getPageList').then((res) => {
    listQuery.value.total = res.total;
    tableData.value = res.records
  }
  ).finally(() => {
    tableloading.value = false
  })
}
//点击领导选择按钮
function ChooesDdld(val) {
  zzlx.value = val;
  memberList.value = ruleForm.value.userids ? ruleForm.value.userids.split(',') : [];
  singleShow.value = false;
  chooseUserVisible.value = true;
}
const getSonValue = (value) => {
  ruleForm.value.usernames = value.map(it => { return it.userName }).toString();
  ruleForm.value.userids = value.map(it => { return it.id }).toString()

};
//风险辨别计划新增
function addUserHander() {
  ruleForm.value = {};
  title.value = "风险辨别计划新增";
  addDiaShow.value = true;
  saveshow.value = true;
  showrkbtn.value = true;
  ruleForm.value.orgName = getItem('deptId').ssdwmc
  ruleForm.value.orgCode = getItem('deptId').ssdwid
  ruleForm.value.draftDepname = getItem('deptId').ssbmmc
  ruleForm.value.draftDepcode = getItem('deptId').ssbmid
  ruleForm.value.files = null
  ruleForm.value.identifyName = ''
}
function onChangebslx(val) {
  if (val == '01') {
    ruleForm.value.identifyName = new Date().getFullYear() + getItem('deptId').ssdwmc + '风险辨识活动'
  } else {
    ruleForm.value.identifyName = ''
  }

}
const handlexg = (row) => {
  getApi({ id: row.id }, '/mosty-jcgl/dangerPlanlist/getInfo').then((res) => {
    ruleForm.value = res
    ruleForm.value.draftDepname = res.draftDepname ? res.draftDepname : res.xtCjbmmc
    // ruleForm.value.usernames = ruleForm.value.usernames ? ruleForm.value.usernames.toString():''
    ruleForm.value.dates = [res.begindate || '', res.enddate || '']
    if (ruleForm.value.status == '1') {
      showrkbtn.value = true
    } else {
      showrkbtn.value = false
    }
    title.value = "风险辨别计划修改";
    addDiaShow.value = true;
    saveshow.value = true;
  })
};
const handleSee = (row) => {
  getApi({ id: row.id }, '/mosty-jcgl/dangerPlanlist/getInfo').then((res) => {
    ruleForm.value = res
    // ruleForm.value.usernames = ruleForm.value.usernames ? ruleForm.value.usernames.toString():''
    ruleForm.value.draftDepname = res.draftDepname ? res.draftDepname : res.xtCjbmmc
    ruleForm.value.dates = [res.begindate || '', res.enddate || '']
    title.value = "风险辨别计划详情";
    addDiaShow.value = true;
    showrkbtn.value = false;
    saveshow.value = false;
  })
};
//列表下发操作按钮
const tabrowxiafa = async (row) => {
  try {
    const res = await getApi({ id: row.id }, '/mosty-jcgl/dangerPlanlist/getInfo');
    ruleForm.value = res;
    ruleForm.value.draftDepname = res.draftDepname ? res.draftDepname : res.xtCjbmmc;
    ruleForm.value.dates = [res.begindate || '', res.enddate || ''];

    // 直接使用弹窗的下发逻辑
    ruleForm.value.status = '2';
    ruleForm.value.files = ruleForm.value.files ? ruleForm.value.files.toString() : null;
    ruleForm.value.usernames = ruleForm.value.usernames && isString(ruleForm.value.usernames) ? ruleForm.value.usernames.split(',') : ruleForm.value.usernames;
    ruleForm.value.userids = ruleForm.value.userids && isString(ruleForm.value.userids) ? ruleForm.value.userids.split(',') : ruleForm.value.userids;
    ruleForm.value.begindate = ruleForm.value.dates[0];
    ruleForm.value.enddate = ruleForm.value.dates[1];

    // 调用修改接口进行下发
    postApi(ruleForm.value, '/mosty-jcgl/dangerPlanlist/edit').then(() => {
      ElMessage.success('下发成功');
      getTabList();
    });

  } catch (error) {

    ElMessage.error('获取数据失败');
  }
}
//删除数据
const handledelete = (row) => {
  postApi({}, `/mosty-jcgl/dangerPlanlist/del/${row.id}`).then((res) => {
    ElMessage.success("删除成功");
    getTabList();
  })
};

//关闭
const handleClose = () => {
  if (!frombt.value) return;
  if (saveshow.value) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        addDiaShow.value = false;
      })
      .catch(() => {
        // catch error
      })
  } else {
    addDiaShow.value = false;
  }

}



//保存
const handleSave = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      ruleForm.value.begindate = ruleForm.value.dates[0]
      ruleForm.value.enddate = ruleForm.value.dates[1]
      delete ruleForm.value.dates
      ruleForm.value.files = ruleForm.value.files ? ruleForm.value.files.toString() : null;
      ruleForm.value.userids = ruleForm.value.userids && isString(ruleForm.value.userids) ? ruleForm.value.userids.split(',') : ruleForm.value.userids;
      ruleForm.value.usernames = ruleForm.value.usernames && isString(ruleForm.value.usernames) ? ruleForm.value.usernames.split(',') : ruleForm.value.usernames
      if (!ruleForm.value.id) {
        ruleForm.value.status = '1'
        submit(ruleForm.value, '新增成功')
      } else if (title.value == "风险辨别计划修改") {
        putmit(ruleForm.value, '修改成功')
      }
      loading.value = false;
    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  })

}
//下发
const saverk = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      ruleForm.value.status = '2'
      ruleForm.value.files = ruleForm.value.files ? ruleForm.value.files.toString() : null;
      ruleForm.value.usernames = ruleForm.value.usernames && isString(ruleForm.value.usernames) ? ruleForm.value.usernames.split(',') : ruleForm.value.usernames;
      ruleForm.value.userids = ruleForm.value.userids && isString(ruleForm.value.userids) ? ruleForm.value.userids.split(',') : ruleForm.value.userids;
      ruleForm.value.begindate = ruleForm.value.dates[0]
      ruleForm.value.enddate = ruleForm.value.dates[1]
      // 状态 0 - 辨识结束 1 - 未下发 2 - 辨识中，新增保存为1，下发为2，修改不传，下发传2
      if (ruleForm.value.id) {
        putmit(ruleForm.value, '下发成功')
      } else {
        submit(ruleForm.value, '下发成功')
      }
    }
  })
}
//新增
function submit(data, val) {
  postApi(data, '/mosty-jcgl/dangerPlanlist/add').then(() => {
    ElMessage.success(val);
    addDiaShow.value = false;
    getTabList();
  })
}
//修改
function putmit(data, val) {
  postApi(data, '/mosty-jcgl/dangerPlanlist/edit').then(() => {
    ElMessage.success(val);
    addDiaShow.value = false;
    getTabList();
  })
}

onMounted(() => {
  getTabList();
})

//关闭弹窗
const closeDialog = () => {
  loading.value = false;
  addDiaShow.value = false
};
//分页
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getTabList();
};
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getTabList();
};
/** 展示市公司下的所有 */
const isShowSgs = ref(false);
/** 展示县公司下的所有 */
const isShowXgs = ref(false);
const isShowYsPage = ref(false);
/** 是否是县公司 */
const isxgs = ref(filterqx('isxgs') == '1')
/**市公司 */
const isgs = ref(filterqx('isgs') == '1')
/**省公司 */
const isSgs = ref(filterqx('isSgs') == '1')
/**省公司且安全部门 */
const isSgsaq = ref(filterqx('saqbm') == '1')
/**市公司安全部门 */
const isgsaq = ref(filterqx('gsaqbm') == '1')
/**县公司安全部门 */
const isxgsaq = ref(filterqx('xgsaqbm') == '1')
const currRow = ref({});
// 辨识进度
const seeInfotable = (row) => {
  currRow.value = row;
  const { orgCode } = row;
  if (!row) return
  // 本级
  if (orgCode.indexOf('XN') > -1) {
    // console.log('本级');
    isShowSgs.value = true;
  } else {
    // 省公司且安全部门 
    if (isSgsaq.value) {
      // console.log('省公司且安全部门');
      isShowSgs.value = true;
      // 市公司且安全部门 
    } else if (isgsaq.value) {
      // console.log('市公司且安全部门');
      isShowSgs.value = true;
      // 县公司
    } else if (isxgsaq.value) {
      // console.log('县公司且安全部门');
      isShowXgs.value = true;
    } else {
      // console.log('其他用户');
      isShowYsPage.value = true;
    }
  }
}
const sgTcClose = () => {
  isShowSgs.value = false
  getTabList()
}
const xgsTcClose = () => {
  isShowXgs.value = false
  getTabList()
}
const ysPageClose = () => {
  isShowYsPage.value = false
  getTabList()
}
</script>

<style lang="scss" scoped>
.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}


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

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

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

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


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

  .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;
  }

}
</style>
