<template>
  <div class="page-container">
    <!-- <div class="progress-bar">
      <span class="label">完成进度：</span>
      <el-progress :percentage="progress" />
    </div> -->
    <div class="layout-box">
      <div class="left-box">
        <div class="info-card">
          <div class="info-card-header">风险单元信息</div>
          <div class="info-card-body">
            <div class="info-card-body-label">辨识单元</div>
            <div class="info-card-body-value">{{ proms?.sitetypeInherent || '-' }}</div>
            <div class="info-card-body-label">风险单元</div>
            <div class="info-card-body-value">{{ proms?.activityfacility || '-' }}</div>
          </div>
          <div class="info-card-body">
            <div class="info-card-body-label">责任部门</div>
            <div class="info-card-body-value">{{ proms?.depname || '-' }}</div>
            <div class="info-card-body-label">责任人</div>
            <div class="info-card-body-value">{{ proms?.username || '-' }}</div>
          </div>
        </div>
        <div class="info-card">
          <div class="info-card-header">固有风险信息</div>
          <div class="info-card-body">
            <div class="info-card-body-label">风险描述（根源）</div>
            <div class="info-card-body-value">{{ proms?.descriptionInherent || '-' }}</div>
            <div class="info-card-body-label">S风险严重程度</div>
            <div class="info-card-body-value">
              <el-tag v-if="proms.sscoreInherent == 1" class="tab-box tab-box-blue">{{ '1' }}</el-tag>
              <el-tag v-else-if="proms.sscoreInherent == 2" class="tab-box tab-box-yellow">{{ '2' }}</el-tag>
              <el-tag v-else-if="proms.sscoreInherent == 3" class="tab-box" type="warning">{{ '3' }}</el-tag>
              <el-tag v-else-if="proms.sscoreInherent == 4" class="tab-box tab-box-red">{{ '4' }}</el-tag>
              <el-tag v-else-if="proms.sscoreInherent == 5" class="tab-box tab-box-red">{{ '5' }}</el-tag>
              <span v-else>{{ proms?.sscoreInherent || '-' }}</span>
            </div>
          </div>
          <div class="info-card-body">
            <div class="info-card-body-label">风险能量释放</div>
            <div class="info-card-body-value">-</div>
            <div class="info-card-body-label">固有风险等级</div>
            <div class="info-card-body-value">
              <el-tag v-if="proms?.risklevelInherent == '1'" class="tab-box tab-box-blue">{{ '低风险(蓝区)' }}</el-tag>
              <el-tag v-else-if="proms?.risklevelInherent == '2'" class="tab-box tab-box-yellow">{{ '一般风险(黄区)'
                }}</el-tag>
              <el-tag v-else-if="proms?.risklevelInherent == '3'" class="tab-box tab-box-orange" type="warning">{{
                '较大风险(橙区)'
                }}</el-tag>
              <el-tag v-else-if="proms?.risklevelInherent == '4'" class="tab-box tab-box-red">{{ '重大风险(红区)' }}</el-tag>
              <el-tag v-else-if="proms?.risklevelInherent == '5'" class="tab-box tab-box-dark-red">{{ '特别重大风险(深红区)'
                }}</el-tag>
              <span v-else>{{ proms?.risklevelInherent || '-' }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="right-box">
        <div class="info-card">
          <div class="info-card-header">现状风险评价</div>
          <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="existingMeasures" style="width: 100%">
              <el-input :disabled="true" type="textarea" rows="2" v-model="proms.existingMeasures" placeholder="请输入现有措施"
                style="width:100%">
              </el-input>
            </el-form-item>
            <el-form-item label="可能存在的风险隐患:" prop="descriptionInherent" style="width: 100%">
              <el-input :disabled="true" type="textarea" rows="2" v-model="proms.descriptionInherent"
                placeholder="请输入现有措施" style="width:100%">
              </el-input>
              <!-- <el-select v-model="proms.consequenseCurrent" 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 v-if="proms.pjfs == '02'" label="可能性(L):" prop="lscore" style="width: 100%">
              <el-select :disabled="true" v-model="proms.lscore" 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="sscore" style="width: 100%">
              <el-select :disabled="true" v-model="proms.sscore" 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="RScore" style="width: 100%">
              <el-input :disabled="true" v-model="proms.RScore" readonly style="width: 100%" />
            </el-form-item>
            <el-form-item label="风险等级:" prop="risklevelCurrent">
              <MOSTY.DictRidioAndSelect :disabled="true" :dictData="D_BZ_FXDJ" v-model="proms.risklevelCurrent"
                style="width: 100%" selectType="select" placeholder='请选择风险单元类型' />
            </el-form-item>
            <el-form-item label="是否保持原措施：" prop="appraiseMaintainMeasures">
              <el-radio-group v-model="proms.appraiseMaintainMeasures" size="small" @change="handleMeasuresChange">
                <el-radio v-for="item in D_FXBS_GKCS_SFBCYCS" :key="item.value" :label="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <div class="table-card">
          <div class="table-header">
            <span class="table-title">补充措施内容</span>
          </div>
          <ControlMeasuresTB ref="controlMeasuresTBRef" class="control-measures-tb" :dangerid="dangerid"
            :chilrenlist="chilrenlist" :tjtype="props.tjtype" :tableData="tableData" :showAddBtn="showAddButton"
            :idlist="idlist" :planid="props.planid" @change="controlMeasuresTBChange" />
        </div>
      </div>
    </div>
    <div class="action-bar">
      <el-button @click="Close">退出评价</el-button>
      <!-- <el-button type="primary" @click="saveFrom(elform)" v-if='props.tjtype != "xq"'>保存</el-button> -->
      <!-- <el-button type="primary" @click="saveAndNext">继续下一条</el-button> -->
    </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 * as MOSTY from "@/components/MyComponents/index";
import ControlMeasuresTB from '@/views/fxgk/aqfxfjgk/component/controlMeasuresTB.vue';
const emits = defineEmits(["close", 'pjcg']);
const { proxy } = getCurrentInstance();
const { D_BZ_LSR_S, D_BZ_LSR_L, D_BZ_FXDJ, D_FXBS_GKCS_SFBCYCS } = proxy.$dict("D_BZ_LSR_S", "D_BZ_LSR_L", "D_BZ_FXDJ", "D_FXBS_GKCS_SFBCYCS");
const rules = reactive({
  descriptionInherent: [{ required: true, message: "请输入可能存在的风险隐患", trigger: "blur" }],
  existingMeasures: [{ required: true, message: "请输入现有可控措施", trigger: "blur" }],
  jcpl: [{ required: true, message: "检查频率不能为空", trigger: "blur" }],
  lscore: [{ required: true, message: "请选择", trigger: "blur" }],
  sscore: [{ required: true, message: "请选择", trigger: "blur" }],
  pjcPoint: [{ required: true, message: "请选择", trigger: "blur" }],
  RScore: [{ required: true, message: "请选择", trigger: "blur" }],
  appraiseMaintainMeasures: [{ 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 listQuery = ref({
  pageCurrent: 1,
  pageSize: 10,
  total: 0
});
const tabs = [{
  label: '评价小组',
  value: 'pjxz'
},
  // {
  //   label: '评价记录',
  //   value: 'pjjl'
  // }
]
const progress = ref(30)
const supplementMeasures = ref([])

/** ---- 弹窗 & 表单 ---- */
const addDialog = ref(false)
const addForm = reactive({
  type: "",
  content: "",
  detail: "",
  planTime: ""
})
function openAddDialog () {
  addDialog.value = true
}
const activeTab = ref('pjxz')
/**危险id */
const dangerid = ref(null)
const props = defineProps({
  saveBtnShow: {
    default: true,
    type: Boolean
  },
  idlist: {
    type: Object,
    default: {}
  },
  planid: {
    type: String,
    default: ''

  },
  tjtype: {
    type: String,
    default: 'pj'
  },
  /** 部门编号 */
  deptcode: String
});
const chilrenlist = ref({})
// 在现有的响应式变量后面添加
const showAddButton = ref(false)


onMounted(() => {
  listQuery.value.bmbsid = proms.value.id ? proms.value.id : props.idlist.bmbsid
  listQuery.value.deptcode = props.deptcode
  chilrenlist.value = props.idlist
  getfrom();
  // 初始化时根据measuresIsKeep设置showAddButton
  if (proms.value.appraiseMaintainMeasures) {
    showAddButton.value = proms.value.appraiseMaintainMeasures != '01';
  } else {
    // 默认情况下隐藏按钮
    showAddButton.value = false;
  }
})
// tab切换
const onTabClick = (e) => {
  const tabName = e.props.name
  activeTab.value = tabName
}

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.RScore = (parseFloat(lecarr.value[0]) * parseFloat(lecarr.value[1]) * parseFloat(lecarr.value[2]) * 1000000).toFixed(2);
      if (proms.value.RScore >= 320) {
        proms.value.risklevel = '4'
      } else if (proms.value.RScore >= 160) {
        proms.value.risklevel = '3'
      } else if (proms.value.RScore >= 70) {
        proms.value.risklevel = '2'
      } else {
        proms.value.risklevel = '1'
      }
    }
    // LSR 模式
  } else {
    if (lecarr.value[0] && lecarr.value[1]) {
      proms.value.RScore = ((parseFloat(lecarr.value[0]) / 4) * (parseFloat(lecarr.value[1]) / 4)).toFixed(2);
      if (proms.value.RScore >= 17) {
        proms.value.risklevel = '4'
      } else if (proms.value.RScore >= 13) {
        proms.value.risklevel = '3'
      } else if (proms.value.RScore >= 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 () {
  proms.value = props.idlist
  // 初始化时根据measuresIsKeep设置showAddButton
  if (proms.value.appraiseMaintainMeasures) {
    showAddButton.value = proms.value.appraiseMaintainMeasures === '01';
  } else {
    // 默认情况下隐藏按钮
    showAddButton.value = false;
  }

  // // 确保 consequenseCurrent 是数组
  // if (proms.value.consequenseCurrent && typeof proms.value.consequenseCurrent === 'string') {
  //   proms.value.consequenseCurrent = proms.value.consequenseCurrent.split(',')
  // } else if (!proms.value.consequenseCurrent) {
  //   proms.value.consequenseCurrent = []  // 初始化为空数组
  // }

  // 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,
  //       consequenseCurrent: res.consequenseCurrent ? res.consequenseCurrent.split(",") : [],
  //       jcpl: res.checkrate && res.checkrate != 'none' ?
  //         res.checkrate + '_' + res.checkratecount : null
  //     }

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

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

  //     // 重新计算 D 值
  //     proms.value.RScore = 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,
        existingMeasures: proms.value.existingMeasures ? proms.value.existingMeasures.toString() : '',//现有可控措施
        // consequenseCurrent: proms.value.consequenseCurrent ? proms.value.consequenseCurrent.join(',') : '',//后果
        risklevelCurrent: proms.value.risklevelCurrent,//当前风险等级
        dangerDescription: proms.value.dangerDescription,//危险描述
        appraiseMaintainMeasures: proms.value.appraiseMaintainMeasures,//是否保持
        // identifyEntityId: props.idlist.identifyEntityId,
        // risklevel: proms.value.risklevel,
        // type: proms.value.type,
      }
      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.consequenseCurrent = proms.value.consequenseCurrent && isString(proms.value.consequenseCurrent) ? proms.value.consequenseCurrent.split(',') : proms.value.consequenseCurrent
        })
      } else {
        // 新的接口地址
        postApi(data, '/mosty-jcgl/bmbs/evaluate').then(res => {
          ElMessage.success("保存成功");
          emits("close", props.deptcode);
        }).finally(() => {
          loading.value = false
          // 恢复 consequenseCurrent 为数组格式
          // proms.value.consequenseCurrent = proms.value.consequenseCurrent && isString(proms.value.consequenseCurrent) ?
          //   proms.value.consequenseCurrent.split(',') : proms.value.consequenseCurrent
        })
      }
    } else {
      // proms.value.consequenseCurrent = proms.value.consequenseCurrent && isString(proms.value.consequenseCurrent) ? proms.value.consequenseCurrent.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);
}

// 处理单选变化
const handleMeasuresChange = (value) => {
  showAddButton.value = value != '01';
  // 调用评价接口
  callAppraiseApi(value);
};
//调用评价接口
const callAppraiseApi = (appraiseMaintainMeasures) => {
  if (!appraiseMaintainMeasures) return;

  const params = {
    id: proms.value.id,
    appraiseMaintainMeasures: appraiseMaintainMeasures,
  };

  loading.value = true;
  postApi(params, '/mosty-jcgl/tbDangerIdentifyResult/appraise').then(res => {
    ElMessage.success("评价成功");
    emits("pjcg");
  }).catch(error => {
    ElMessage.error("评价失败");
  }).finally(() => {
    loading.value = false;
  });
};
</script>

<style scoped lang="scss">
.page-container {
  padding: 20px;
}

.progress-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .label {
    margin-right: 12px;
    font-weight: 500;
  }
}

.layout-box {
  display: flex;
  gap: 20px;
}

.left-box {
  width: 45%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.right-box {
  width: 55%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card {
  border-radius: 4px;
  padding: 16px;
}

.info-card-header {
  font-weight: bold;
  font-size: 16px;
  background: #B4C9C4;
  text-align: center;
  padding: 16px;
}

.info-card-body {
  display: flex;

  .info-card-body-label {
    width: 15%;
    padding: 8px;
    font-size: 12px;
    background: #E1EDEA;
    text-align: center;
    border: 1px solid #C2D3CF;
  }

  .info-card-body-value {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 35%;
    padding: 8px;
    font-size: 12px;
    text-align: center;
    border: 1px solid #C2D3CF;
  }
}

.table-card {
  background: #fff;
  border-radius: 4px;
  padding: 16px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;

  .table-title {
    font-size: 14px;
    font-weight: bold;
  }
}

.action-bar {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.risk-form .el-form-item {
  width: 50%;
  margin-bottom: 10px;
}

.tab-box {
  font-size: 11px;
  margin: 0px;

  .tab-box-blue {
    --el-tag-bg-color: #7f99e7;
    --el-tag-border-color: #268ae8;
    --el-tag-text-color: #1f6eb4;
    --el-tag-hover-color: #1551b2;
  }

  .tab-box-yellow {
    --el-tag-bg-color: #e7e57f;
    --el-tag-border-color: #e8e526;
    --el-tag-text-color: #dec90d;
    --el-tag-hover-color: #e7d10e;
  }

  .tab-box-orange {
    --el-tag-bg-color: #e7a97f;
    --el-tag-border-color: #e87726;
    --el-tag-text-color: #c54404;
    --el-tag-hover-color: #cd580a;
  }

  .tab-box-red {
    --el-tag-bg-color: #e78b7f;
    --el-tag-border-color: #e84026;
    --el-tag-text-color: #cf220f;
    --el-tag-hover-color: #d21f0b;
  }

}
</style>
