<template>
  <div>
    <!-- 表格 -->
    <div class="box-a">
      <div class="leftbox">
        <el-form class="mosty-from-wrap pjindex-form" title="我的评价" ref="elform" label-width="130px" :model="proms"
          :inline="true" :rules="rules" :disabled='props.tjtype == "xq"'>
          <el-form-item label="风险描述:" prop="dangerDescription" style="width: 100%">
            <el-input v-model="proms.dangerDescription" type="textarea" :rows="2" show-word-limit maxlength="300" />
          </el-form-item>
          <el-form-item label="风险类型:" prop="type" style="width: calc(100%)">
            <el-select v-model="proms.type" style="width: 100%" disabled>
              <el-option v-for="item in D_BZ_FXLX" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查频率:" prop="jcpl" style="width: 100%">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_JCBZPL" v-model="proms.jcpl" style="width: 100%"
              selectType="select" placeholder='请选择检查频率' />
          </el-form-item>
          <el-form-item label="可能产生的后果:" prop="consequense" style="width: 100%">
            <el-select v-model="proms.consequense" style="width: 100%" multiple>
              <el-option v-for="item in D_BZ_KNFXHGLX" :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> -->

          <!-- 现有措施 start -->
          <el-form-item label="现有措施:" prop="existingMeasures" style="width: 100%">
            <el-input type="textarea" rows="2" v-model="proms.existingMeasures" placeholder="请输入现有措施"
              style="width:100%">
            </el-input>
          </el-form-item>

          <!-- 加强措施 -->
          <!-- <el-form-item label="加强措施:" prop="strengtheningMeasures" style="width: 100%">
            <el-input type="textarea" rows="2" v-model="proms.strengtheningMeasures" placeholder="请输入加强措施"
              style="width:100%">
            </el-input>
          </el-form-item> -->

          <!-- LECD 模式 -->
          <el-form-item v-if="proms.pjfs == '01'" label="L:" prop="pjlPoint" style="width: 100%">
            <el-select v-model="proms.pjlPoint" style="width: 100%">
              <el-option v-for="item in D_TB_LECD_L" :key="item.value" :label="item.label" :value="item.value"
                @click.native="labelClick(item.value, 0)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="proms.pjfs == '01'" label="E:" prop="pjePoint" style="width: 100%">
            <el-select v-model="proms.pjePoint" style="width: 100%">
              <el-option v-for="item in D_TB_LECD_E" :key="item" :label="item.label" :value="item.value"
                @click.native="labelClick(item.value, 1)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="proms.pjfs == '01'" label="C:" prop="pjcPoint" style="width: 100%">
            <el-select v-model="proms.pjcPoint" style="width: 100%">
              <el-option v-for="item in D_TB_LECD_C" :key="item" :label="item.label" :value="item.value"
                @click.native="labelClick(item.value, 2)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="proms.pjfs == '01'" label="D:" prop="pjdPoint" style="width: 45%">
            <el-input v-model="proms.pjdPoint" readonly style="width: 100%" />
          </el-form-item>

          <!-- L-S-R模式 -->
          <el-form-item v-if="proms.pjfs == '02'" label="L:" prop="pjlPoint" style="width: 100%">
            <el-select v-model="proms.pjlPoint" style="width: 100%">
              <el-option v-for="item in D_BZ_LSR_L" :key="item.value" :label="item.label" :value="item.value"
                @click.native="labelClick(item.value, 0)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="proms.pjfs == '02'" label="S:" prop="pjePoint" style="width: 100%">
            <el-select v-model="proms.pjePoint" style="width: 100%">
              <el-option v-for="item in D_BZ_LSR_S" :key="item" :label="item.label" :value="item.value"
                @click.native="labelClick(item.value, 1)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="proms.pjfs == '02'" label="R:" prop="pjdPoint" style="width: 100%">
            <el-input v-model="proms.pjdPoint" readonly style="width: 100%" />
          </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 class='btnBoxs' style="display: flex;justify-content: center;">
          <el-button type="primary" @click="saveFrom(elform)" v-if='props.tjtype != "xq"'>
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
        </div>
      </div>

      <!-- 上面右边的table -->
      <div class="tabBox2 pj-index-tab">
        <div style="display: flex;justify-content:space-between;margin: 10px 10px 10px 0px;align-items: center;">
          <!-- tabs页面 -->
          <div class="yhzl-wrapper" style="height: auto;">
            <div class="header" style="margin-bottom:0px">
              <div class="bottom" style="padding: 0px;">
                <el-tabs class="yhzlbox" v-model="activeTab" type="card" @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>
          <div class='btnBoxs'>
            <el-button type="primary" @click="Close">
              <el-icon>
                <DocumentDelete />
              </el-icon>
              <span>关闭</span>
            </el-button>
          </div>
        </div>

        <div style="height: 350px;" v-if="activeTab == 'pjxz'">
          <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloadings"
            :isSelect="false" :isSort="false" style="width: 100%;" actionsW="150px">
            <template #type="{ row }">
              <dict-tag :options="D_BZ_FXLX" :value="row.type" :tag="false" />
            </template>
            <template #consequense="{ row }">
              <dict-tag :options="D_BZ_KNFXHGLX" :value="row.consequense" :tag="true" />
            </template>
            <template #pjdPoint="{ row }">
              <span>{{ row.pjdPoint ? row.pjdPoint : '--' }}</span>
            </template>
            <!-- <template #actions="{ row }">
              <span v-if="row.risklevel == '-'">待评价</span>
              <span v-else-if='props.tjtype != "xq" && row.risklevel != "-"' class="operesee" @click="handlehz(row)">
                <el-icon>
                  <Compass />
                </el-icon>应用</span>
              <span v-else>--</span>
            </template> -->
          </MOSTY.Table>
        </div>
        <div style="height: 350px;" v-if="activeTab == 'pjjl'">
          <MOSTY.Table :table-columns="tableColumn2" :tableData="tableData" :tableloading="tableloadings"
            :isSelect="false" :isSort="false" style="width: 100%;" actionsW="150px">
            <template #type="{ row }">
              <dict-tag :options="D_BZ_FXLX" :value="row.type" :tag="false" />
            </template>
            <template #consequense="{ row }">
              <dict-tag :options="D_BZ_KNFXHGLX" :value="row.consequense" :tag="true" />
            </template>
            <template #pjdPoint="{ row }">
              <span>{{ row.pjdPoint ? row.pjdPoint : '--' }}</span>
            </template>
            <template #actions="{ row }">
              <span class="operesee" @click="handleinfo(row)">
                <el-icon>
                  <Compass />
                </el-icon>详情</span>
            </template>
          </MOSTY.Table>
        </div>
        <ControlMeasuresTB ref="controlMeasuresTBRef" class="control-measures-tb" :dangerid="dangerid"
          :chilrenlist="chilrenlist" :tjtype="props.tjtype" :tableData="tableData" @change="controlMeasuresTBChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
// 引入
import { defineProps, onMounted, getCurrentInstance, defineEmits, ref, reactive, watch } from 'vue'
import { ElMessage } from "element-plus";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { isString } from '@/utils/tools.js';
import * as MOSTY from "@/components/MyComponents/index";
import ControlMeasuresTB from '@/views/fxgk/aqfxfjgk/component/controlMeasuresTB.vue';
const emits = defineEmits(["close"]);
const { proxy } = getCurrentInstance();
const { D_BZ_KNFXHGLX, D_BZ_JCBZPL, D_TB_LECD_L, D_TB_LECD_E, D_TB_LECD_C,
  D_BZ_FXLX, D_BZ_LSR_S, D_BZ_LSR_L, D_DBZ_YHDJ, NYHBZ, NSFBXSCTP

} = proxy.$dict("D_BZ_KNFXHGLX", "D_BZ_JCBZPL", "D_TB_LECD_L", "D_TB_LECD_E", 'D_TB_LECD_C', 'D_BZ_FXLX',
  "D_BZ_LSR_S", "D_BZ_LSR_L", "D_DBZ_YHDJ", "NYHBZ", "NSFBXSCTP");
const elform = ref();
const peoplelistid = ref(null);
const rules = reactive({
  consequense: [{ required: true, message: "请选择可能产生的后果", trigger: "blur" }],
  existingMeasures: [{ required: true, message: "请输入现有措施", trigger: "blur" }],
  jcpl: [{ required: true, message: "检查频率不能为空", trigger: "blur" }],
  pjlPoint: [{ required: true, message: "请选择", trigger: "blur" }],
  pjePoint: [{ required: true, message: "请选择", trigger: "blur" }],
  pjcPoint: [{ required: true, message: "请选择", trigger: "blur" }],
  pjdPoint: [{ required: true, message: "请选择", trigger: "blur" }],
  type: [{ required: true, message: "请选择", trigger: "blur" }],
  dangerDescription: [{ required: true, message: "请输入风险描述", trigger: "blur" }],
});
const loading = ref(false);
const fromData = ref({})
const proms = ref({})
/**控制措施 组件 */
const controlMeasuresTBRef = ref(null);
const plan = ref({});
const dangerDescription = ref('');
const lecarr = ref([])
const tableData = ref([])
const tableData2 = ref([])
const tableloadings = ref(false)
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10,
  total: 0
});
const tabs = [{
  label: '评价小组',
  value: 'pjxz'
},
  // {
  //   label: '评价记录',
  //   value: 'pjjl'
  // }
]
const activeTab = ref('pjxz')
/**危险id */
const dangerid = ref(null)
const props = defineProps({
  saveBtnShow: {
    default: true,
    type: Boolean
  },
  idlist: {
    type: Object,
    default: {}

  },
  tjtype: {
    type: String,
    default: 'pj'
  },
  /** 部门编号 */
  deptcode: String
});
const tableColumn = ref([
  {
    title: "姓名",
    prop: "teamMemberUserName",
  },
  {
    title: "部门",
    prop: "teamMemberUserOrgName",
    sort: true
  },
  {
    title: "岗位",
    prop: "teamMemberUserPositionName",
    sort: true
  },
])
const tableColumn2 = ref([
  {
    title: "修改时间",
    prop: "updateTime",

  },
  {
    title: "修改人",
    prop: "updateUserName",

  },
  {
    title: "修改人部门",
    prop: "departmentName",
  },

  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const chilrenlist = ref({})
onMounted(() => {
  listQuery.value.bmbsid = proms.value.id ? proms.value.id : props.idlist.bmbsid
  listQuery.value.deptcode = props.deptcode
  chilrenlist.value = props.idlist
  getfrom();
})
// tab切换
const onTabClick = (e) => {
  const tabName = e.props.name
  activeTab.value = tabName
}
// 评价记录详情
const handleinfo = (row) => {

}
function labelClick(val, lab) {
  lecarr.value[lab] = val
  // <!-- LECD 模式 -->
  if (proms.value.pjfs == '01') {
    if (lecarr.value[0] && lecarr.value[1] && lecarr.value[2]) {
      proms.value.pjdPoint = (parseFloat(lecarr.value[0]) * parseFloat(lecarr.value[1]) * parseFloat(lecarr.value[2]) * 1000000).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'
      }
    }
    // LSR 模式
  } else {
    if (lecarr.value[0] && lecarr.value[1]) {
      proms.value.pjdPoint = ((parseFloat(lecarr.value[0]) / 4) * (parseFloat(lecarr.value[1]) / 4)).toFixed(2);
      if (proms.value.pjdPoint >= 17) {
        proms.value.risklevel = '4'
      } else if (proms.value.pjdPoint >= 13) {
        proms.value.risklevel = '3'
      } else if (proms.value.pjdPoint >= 8) {
        proms.value.risklevel = '2'
      } else {
        proms.value.risklevel = '1'
      }
    }

  }


}
/** 获取当前等级数值 计算LSR
 * @param {*} lecarr
 * @param {*} pjfs
 */
function getPjdPoint(lecarr, pjfs) {
  if (pjfs == '01') {
    // L-E-C-D模式
    if (lecarr.value[0] && lecarr.value[1] && lecarr.value[2]) return (parseFloat(lecarr.value[0]) * parseFloat(lecarr.value[1]) * parseFloat(lecarr.value[2]) * 1000000).toFixed(2);
    // 'L-S-R'模式
  } else {
    if (lecarr.value[0] && lecarr.value[1]) return ((parseFloat(lecarr.value[0]) / 4) * (parseFloat(lecarr.value[1]) / 4)).toFixed(2);
  }
  return null
}
//辨识评价-评价-页面详情
function getfrom() {
  let params = {
    bmbsid: props.idlist.bmbsid,
  }
  getApi(params, '/mosty-jcgl/dangerPlanlist/getBmbmInfo').then((res) => {
    if (res) {
      dangerid.value = res.dangerid
      fromData.value.shortid = res.shortid;
      fromData.value.sitename = res.sitename;
      dangerDescription.value = res.dangerDescription
      // 直接使用响应数据赋值给 proms
      proms.value = {
        ...res,
        consequense: res.consequense ? res.consequense.split(",") : [],
        jcpl: res.checkrate && res.checkrate != 'none' ?
          res.checkrate + '_' + res.checkratecount : null
      }

      // 初始化 lecarr 数组 - 确保转换为字符串
      lecarr.value[0] = res.pjlPoint ? res.pjlPoint.toString() : null;
      lecarr.value[1] = res.pjePoint ? res.pjePoint.toString() : null;
      lecarr.value[2] = res.pjcPoint ? res.pjcPoint.toString() : null;

      // 设置表单的 L、E、C 值 - 确保转换为字符串
      proms.value.pjlPoint = lecarr.value[0];
      proms.value.pjePoint = lecarr.value[1];
      proms.value.pjcPoint = lecarr.value[2];

      // 重新计算 D 值
      proms.value.pjdPoint = getPjdPoint(lecarr, res.pjfs);

      getpepoList()
    } else {
      getpepoList()
      proms.value = JSON.parse(JSON.stringify(tableData.value[0]));
      peoplelistid.value = tableData.value[0].id
    }

  })
}
//	辨识评价-评价-查询评价小组情况
function getpepoList() {
  let params = {
    bmbsid: props.idlist.id,
  }
  getApi(params, '/mosty-jcgl/tbDangerIdentifyEvaluateTeam/selectMemberUserInfoListByAppraise').then((res) => {
    tableData.value = res
  })
}

const controlMeasuresTBChange = (val) => {
  tableData2.value = val.map(item => {
    return {
      ...item,
      bmbsid: props.idlist.bmbsid
    }
  })
}
//保存
const saveFrom = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      let data = {
        bmbsid: props.idlist.bmbsid,
        consequense: proms.value.consequense ? proms.value.consequense.toString() : '',
        // checkrate: proms.value.jcpl ? proms.value.jcpl.split('_')[0] : null,
        // checkratecount: proms.value.jcpl ? proms.value.jcpl.split('_')[1] : null,
        dangerDescription: proms.value.dangerDescription,
        identifyEntityId: props.idlist.identifyEntityId,
        // id: proms.value.id ? proms.value.id : peoplelistid.value,
        // pjcPoint: proms.value.pjcPoint,
        // pjdPoint: proms.value.pjdPoint,
        // pjePoint: proms.value.pjePoint,
        // pjlPoint: proms.value.pjlPoint,
        risklevel: proms.value.risklevel,
        type: proms.value.type,
        // existingMeasures: proms.value.existingMeasures,
        // resultList: tableData2.value
      }
      if (props.tjtype == 'sy') {
        //审验
        postApi(data, `/mosty-jcgl/dangerPlanlist/bspj/pj/sy`).then(res => {
          ElMessage.success("审验成功");
          emits("close", props.deptcode);
        }).finally(() => {
          loading.value.false
          // 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 {
        // 新的接口地址
        postApi(data, '/mosty-jcgl/bmbs/evaluate').then(res => {
          ElMessage.success("保存成功");
          emits("close", props.deptcode);
        }).finally(() => {
          loading.value = false
          // 恢复 consequense 为数组格式
          proms.value.consequense = proms.value.consequense && isString(proms.value.consequense) ?
            proms.value.consequense.split(',') : proms.value.consequense
        })
      }
    } else {
      // proms.value.consequense = proms.value.consequense && isString(proms.value.consequense) ? proms.value.consequense.split(',') : null
      ElMessage.error("请输入必填项!");
    }
  })
}
//返回
function Close() {
  // if (props.tjtype != "xq") {
  //   proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
  //     .then(() => {
  //       emits("close", props.deptcode);
  //     })
  //     .catch(() => {
  //       // catch error
  //     })
  // } else {
  //   emits("close", props.deptcode);
  // }
  emits("close", props.deptcode);
}
</script>

<style lang="scss" scoped>
.el-form {
  display: flex;
  justify-content: space-between;
    flex-wrap: wrap;
  
  }
  
  .el-form-item {
    margin-bottom: 40px !important;
  }
  
  .box-a {
    display: flex;
    justify-content: space-between;
  }
  
  
  
  .el-select {
    width: 150px;
  }
  
  .btnBox {
    position: absolute;
    right: 15px;
    top: 9px;
  }
  
  .bs-title {
    color: red;
    margin: 10px;
  }
  
  .leftbox {
    width: 55%;
    margin-right: 40px;
    margin-top: 20px;
  }
  
  .control-measures-tb {
    margin-top: 10px;
    flex: 1;
    overflow: auto;
  }
  
  .tabBox2 {
    width: 45%;
    display: flex;
    flex-direction: column;
  }
  
  .fil-bbox {
    display: flex;
  
    .font {
      color: #000;
      font-size: 16px;
      font-weight: 600;
      margin: 10px;
  
      .labs {
        color: #999494;
      }
    }
  }
  
  .operates {
    cursor: pointer;
    color: yellowgreen !important;
    display: inline-block;
    width: 40px;
    height: 23px;
    border: 1px solid #000;
    margin: 0 5px;
    background-color: #fff;
  }
  
  .operated {
    cursor: pointer;
    color: #fff !important;
    display: inline-block;
    width: 40px;
    height: 23px;
    border: 1px solid #000;
    margin: 0 5px;
    background-color: #f11515;
  }
  
  .redfont {
    color: rgb(245, 34, 34) !important;
  }
  
  .fxdjspan {
    display: inline-block;
    width: 100%;
    padding-top: 3px;
    padding-bottom: 3px;
    padding-left: 5px;
    border-radius: 5px;
    color: #fff !important;
  }
  
  .reds {
    background-color: #e80000;
  }
  
  .orgs {
    background-color: #ff8040;
}

.blus {
  background-color: #e2d101;
}

.gres {
  background-color: #0080ff;
}
</style>
