<template>
  <div>
    <MOSTY.PageTree :pageTitle="'风险控制措施'" :searchType="'01'" @getDeptId="getdeptId">
      <template #serach>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
        <el-divider />
        <div class="btnBox">
          <el-button type="primary" @click="onloadExcel" v-loading="loading">
            <el-icon>
              <Download />
            </el-icon>
            <span>导出</span>
          </el-button>
        </div>
      </template>
      <template #table>
        <section class="eltab9">
          <MOSTY.Table :table-columns="tableColumns" :tableData="tableData" :tableloading="tableloading"
            :isSelect="false" :isSort="false" :tableHeight="'100%'" @SortChange="SortChange">
            <template #risklevel="{ 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>
            <template #riskName="{ row }">
              <span v-if="row.preName && row.riskName">{{ row.preName }}>{{ row.riskName }}</span>
              <span v-else>无</span>
            </template>
            <template #actions="{ row }">
              <span class="operedit" @click="See(row)"> <el-icon>
                  <EditPen />
                </el-icon>控制</span>

            </template>
          </MOSTY.Table>
        </section>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="listQuery" @changeNo="handleCurrentChange" @changeSize="handleSizeChange" />
        </div>
      </template>
    </MOSTY.PageTree>

    <!-- 修改 -->
    <el-dialog v-model="comprehensiveShow" :title="logtitle" width="50%" :before-close="closeDialog">
      <div>
        <el-form class="mosty-from-wrap" ref="elform" label-width="130px" :model="ruleForm" :inline="true"
          :rules="rules">
          <el-form-item label="风险描述:" prop="dangerDescription">
            <el-input v-model="proms.dangerDescription" type="textarea" show-word-limit style="width: 755px" />
          </el-form-item>
          <el-form-item label="可能产生的后果:" prop="consequense" style="width: 100%">
            <el-select v-model="proms.consequense" multiple style="width: 755px" placeholder="请选择可能产生的后果">
              <el-option v-for="item in D_TB_KNCSDHG" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="控制措施:" prop="controls" style="width: 100%">
            <el-select v-model="proms.controls" multiple style="width: 755px">
              <el-option v-for="item in D_TB_WXYKZCS" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="L:" prop="pjlPoint" style="width: 100%">
            <el-select v-model="proms.pjlPoint" style="width: 755px">
              <el-option v-for="item in D_TB_LECD_L" :key="item.value" :label="item.label" :value="item.value"
                @click.native="labelClick(item.label, 0)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="E:" prop="pjePoint" style="width: 100%">
            <el-select v-model="proms.pjePoint" style="width: 755px">
              <el-option v-for="item in D_TB_LECD_E" :key="item" :label="item.label" :value="item.value"
                @click.native="labelClick(item.label, 1)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="C:" prop="pjcPoint" style="width: 100%">
            <el-select v-model="proms.pjcPoint" style="width: 755px">
              <el-option v-for="item in D_TB_LECD_C" :key="item" :label="item.label" :value="item.value"
                @click.native="labelClick(item.label, 2)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="评价分数:" prop="pjdPoint" style="width: 100%">
            <el-input v-model="proms.pjdPoint" style="width: 755px" />
          </el-form-item>
          <el-form-item label="风险等级:" style="width: 100%">
            <span v-if="proms.risklevel == '4'" class="fxdjspan reds">重大风险</span>
            <span v-if="proms.risklevel == '3'" class="fxdjspan orgs">较大风险</span>
            <span v-if="proms.risklevel == '2'" class="fxdjspan blus">一般风险</span>
            <span v-if="proms.risklevel == '1'" class="fxdjspan gres">低风险</span>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">

          <el-button @click="saveFrom(elform)" v-loading='loadingshow'> <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span></el-button>
          <el-button @click="closeDialog"> <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span></el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, watch, getCurrentInstance } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { filterYear } from "@/utils/auth.js";
import { ElMessage } from "element-plus";
import { isString } from '@/utils/tools.js';
import { exportXlsx } from "@/excel/Export2Excel.js";
const { proxy } = getCurrentInstance();
const { D_TB_KNCSDHG, D_TB_WXYKZCS, D_TB_LECD_L, D_TB_LECD_E, D_TB_LECD_C, D_BZ_FXDJ } =
  proxy.$dict("D_TB_KNCSDHG", "D_TB_WXYKZCS", "D_TB_LECD_L", "D_TB_LECD_E", 'D_TB_LECD_C', 'D_BZ_FXDJ');
const elform = ref();
const rules = reactive({
  dangerDescription: [{ required: true, message: "请输入风险描述", trigger: "blur" }],
  consequense: [{ required: true, message: "请选择可能产生的后果", trigger: "blur" }],
  // controls: [{ required: true, message: "请选择控制措施", trigger: "blur" }],
  pjlPoint: [{ required: true, message: "请选择L", trigger: "blur" }],
  pjePoint: [{ required: true, message: "请选择E", trigger: "blur" }],
  pjdPoint: [{ required: true, message: "请输入评价分数", trigger: "blur" }],

})
const loadingshow = ref(false)
const comprehensiveShow = ref(false);
const lecarr = ref([])
const proms = ref({
})
const id = ref(null)
const logtitle = ref('控制')
const tableData = ref([]);
const searchArr = reactive([
  {
    showType: "select",
    prop: "year",
    width: '250px',
    defaultVal: new Date().getFullYear(),
    options: filterYear(7),
  },
  {
    showType: "input",
    prop: "objname",
    width: '250px',
    placeholder: '请输入请输入对象名称'
  },

]);
const tableColumns = reactive([
  {
    title: "风险编号",
    prop: "shortid"
  },
  {
    title: "对象名称",
    prop: "objname"
  },
  {
    title: "风险单元",
    prop: "riskcell"
  },
  {
    title: "风险描述",
    prop: "dangerDescription",

  },
  {
    title: "评价分数",
    prop: "pjdPoint",
  },
  {
    title: "风险等级",
    prop: "risklevel",
    slot: true
  },
  {
    title: "动态情况",
    prop: "riskName",
    slot: true
  },
  {
    title: "责任部门",
    prop: "depname"
  },
  {
    title: "操作",
    prop: "actions",
    fixed: 'right',
    slot: true
  }
])
// 分页
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  total: 0,
  year: new Date().getFullYear()
});
const tableloading = ref(false);
// 初始化
onMounted(() => {

});
//选择右侧部门
const getdeptId = (val) => {
  listQuery.orgcode = val.id;
  listQuery.pageCurrent = 1;
  getTableData();
};
//查询
function onSearch(obj) {
  listQuery.year = obj.year;
  listQuery.objname = obj.objname;
  listQuery.pageCurrent = 1;
  getTableData();
}
watch(() => listQuery.year,
  () => {
    getTableData()
  }
)
// 查询列表数据
function getTableData() {
  tableloading.value = true;
  getApi(listQuery, '/mosty-jcgl/fxkz/getPageList').then(res => {
    if (res.records) {
      res.records.forEach(item => {
        // if (item.controls) {
        //   item.controls = item.controls.split(',')
        // }
      })
      tableData.value = res.records;
      listQuery.total = res.total;
      listQuery.pageSize = res.size;
    }
  }).finally(() => {
    tableloading.value = false;
  })
}
//查看
const See = (row) => {
  id.value = row.id
  logtitle.value = '控制——' + row.dangerDescription
  getxqlog()
  comprehensiveShow.value = true
}
function getxqlog() {
  getApi({ bmbsid: id.value }, '/mosty-jcgl/dangerPlanlist/getBmbmInfo').then(res => {
    if (res) {
      // res.controls = res.controls.split(',')
      res.consequense = res.consequense.split(',')
      proms.value = res
      lecarr.value[0] = proms.value.pjlPoint;
      lecarr.value[1] = proms.value.pjePoint;
      lecarr.value[2] = proms.value.pjcPoint;
    }
  })
}
function labelClick(val, lab) {
  var grade = val.substring(val.lastIndexOf("（") + 1, val.lastIndexOf("）"));
  lecarr.value[lab] = grade
  if (lecarr.value.length == 3) {
    proms.value.pjlPoint = lecarr.value[0] ? parseFloat(lecarr.value[0]) : Number(1)
    proms.value.pjePoint = lecarr.value[1] ? parseFloat(lecarr.value[1]) : Number(1)
    proms.value.pjcPoint = lecarr.value[2] ? parseFloat(lecarr.value[2]) : Number(1)
    proms.value.pjdPoint = (proms.value.pjlPoint * proms.value.pjePoint * proms.value.pjcPoint).toFixed(2);
    if (proms.value.pjdPoint >= 320) {
      proms.value.risklevel = '4'
    } else if (proms.value.pjdPoint >= 160) {
      proms.value.risklevel = '3'
    } else if (proms.value.pjdPoint >= 70) {
      proms.value.risklevel = '2'
    } else {
      proms.value.risklevel = '1'
    }
  }
}
//保存控制
const saveFrom = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loadingshow.value = true
      // proms.value.controls = proms.value.controls ? proms.value.controls.toString() : ''
      proms.value.consequense = proms.value.consequense ? proms.value.consequense.toString() : ''
      postApi(proms.value, '/mosty-jcgl/fxkz/kzSave').then(res => {
        ElMessage.success("保存成功");
        comprehensiveShow.value = false
        loadingshow.value = false
        getTableData()
      }).finally(() => {
        // proms.value.controls = proms.value.controls&&isString(proms.value.controls) ? proms.value.controls.split(',') : null
        proms.value.consequense = proms.value.consequense && isString(proms.value.consequense) ? proms.value.consequense.split(',') : proms.value.consequense
      })
    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  })

}

const closeDialog = () => {
  if (!props.isShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        comprehensiveShow.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    comprehensiveShow.value = false
  }

};
//页码发生变化
const handleCurrentChange = (val) => {
  listQuery.pageCurrent = val;
  getTableData();
};
//查询条数发生变化
const handleSizeChange = (val) => {
  listQuery.pageSize = val;
  getTableData();
};
const loading = ref(false)
//导出Excel
function onloadExcel() {
  let title = {
    shortid: '风险编号',
    objname: '对象名称',
    riskcell: '风险单元',
    dangerDescription: '风险描述',
    // controlname: '控制措施',
    pjdPoint: '评价分数',
    risklevels: '风险等级',
    depname: '责任部门',
  }
  let obj = { ...listQuery };
  obj.pageSize = 100000
  loading.value = true
  getApi(obj, '/mosty-jcgl/fxkz/exportData').then((res) => {
    if (res) {
      let data = res
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // if (data[i].controls.includes(",")) {
          //   data[i].controlname = data[i].controls.split(',');
          //   data[i].controlname = data[i].controlname.forEach(item => {
          //     item = proxy.$getDictVal(item, D_TB_WXYKZCS);
          //   }).toString()
          // } else {
          //   data[i].controlname = proxy.$getDictVal(data[i].controls, D_TB_WXYKZCS);
          // }

          if (data[i].consequense.includes(",")) {
            data[i].consequensename = data[i].consequense.split(',');
            data[i].consequensename = data[i].consequensename.forEach(item => {
              item = proxy.$getDictVal(item, D_TB_KNCSDHG);
            }).toString()
          } else {
            data[i].consequensename = proxy.$getDictVal(data[i].consequense, D_TB_KNCSDHG);
          }

          if (data[i].risklevel == '4') {
            data[i].risklevels = '红色'
          }
          if (data[i].risklevel == '3') {
            data[i].risklevels = '橙色'
          }
          if (data[i].risklevel == '2') {
            data[i].risklevels = '黄色'
          }
          if (data[i].risklevel == '1') {
            data[i].risklevels = '蓝色'
          }

        }
        let tablename = '风险控制.xlsx'
        exportXlsx(title, data, '风险控制', tablename);
        loading.value = false

      } else {
        ElMessage.warning('暂无数据');
        loading.value = false
      }
    }

  }).catch(err => {
    loading.value = false
  })
}

</script>

<style lang="scss" scoped>
.el-form {
  width: 886px;
  display: block;
}

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}


.detail {
  border-top: 1px dashed green;
  padding: 15px 100px;
  display: flex;
  justify-content: space-between;

  div {
    width: 238px;
    height: 101px;
    text-align: center;

    span {
      font-size: 18px;
      display: block;
      width: 238px;
      height: 37px;
      line-height: 37px;
      padding: 0;
      margin: 0;
      background-color: #c1c0be;
    }

    h2 {
      font-size: 39px;
      width: 238px;
      height: 68px;
      line-height: 68px;
      padding: 0;
      margin: 0;
    }
  }
}

.right-box {
  display: flex;
}

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