<template>
  <div>
    <div class="anquantr-container">
      <div class="tab-container tab-container-scope">
        <el-tabs 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 v-if="activeTab === 'bspjindex'" class="btnBox">
      <!-- 安全员、科长 -->
      <div v-if="['AQY', 'KZ'].includes(props.initPage.role) && ['21', '20'].includes(listQuery.stage)">
        <el-button type="primary" @click="handlehz">
          <span>提交审核</span>
        </el-button>
        <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要驳回?"
          @confirm="bigDangerReject">
          <template #reference>
            <el-button type="primary" class='mr10' :disabled="!isAqbm || !proms?.identifyEntityId">
              <span>重大风险辨识遗漏驳回</span>
            </el-button>
          </template>
        </el-popconfirm>

        <!-- <el-button type="primary" @click="changbs" class='mr10' :disabled="!isAqbm">
          <span>设置评价小组</span>
        </el-button> -->

      </div>
      <el-button type="primary" @click="Close">
        <el-icon>
          <ArrowLeft />
        </el-icon>
        <span>返回</span>
      </el-button>
    </div>
    <!-- 表格 -->
    <div v-if="activeTab === 'bspjindex'" class="box-a">
      <div>
        <div style="display: flex;justify-content: space-between;">
          <div style="width: 35%;height:calc(100vh - 184px);">
            <MOSTY.Table highlightCurrentRow :table-columns="tableColumn" :tableData="tableData1"
              :tableloading="tableloading" :isSelect="false" :isSort="false" style="width: 100%;" actionsW="100"
              @rowClick="rowClick">
              <template #num="{ row }">
                <span>{{ row.orangePointCount + row.redPointCount + row.yellowPointCount
                  + row.bluePointCount }}</span>
              </template>
              <template #stage="{ row }">
                <dict-tag :options="GZ_D_ENT_STAGE" :value="row.stage" :tag="false" />
              </template>
              <template #actions="{ row }">
                <span class="operesee" v-if="row.stage == '21' || (row.orangePointCount + row.redPointCount + row.yellowPointCount
                  + row.bluePointCount) > 0" @click.stop="handlexg(row)">查看</span>
                <span v-else>--</span>
              </template>
            </MOSTY.Table>
          </div>
          <div style="flex: 1;margin-left: 10px;margin-right:10px">
            <div style="height: calc(100vh - 249px)">
              <el-table ref="mulRefs" stripe :data="tableData2" style="width: 100%;height:100%;" :height="tableHeight"
                border>
                <el-table-column label="风险单元" property="objname">
                </el-table-column>
                <el-table-column label="风险描述" property="dangerDescription" show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="风险等级" property="risklevel" width='150'>
                  <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-column property="isPj" label="状态" width='100'>
                  <template #default="{ row }">
                    <!-- 状态 01.评价中 02.申验中 03.完成 -->
                    <span v-if="row.status == '01'">评价中</span>
                    <!-- <span v-if="row.status == '02'">审验中</span> -->
                    <span v-if="row.status == '03'">已评价</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width='250'>
                  <template #default="{ row }">
                    <span class="operesee" @click="handlepj(row, 'pj')"><el-icon>
                        <Compass />
                      </el-icon>评价
                    </span>
                    <!-- <span class="operedit" @click="handlepj(row, 'sy')"
                      v-if="props.initPage.role == 'KZ' && row.status == '02'"><el-icon>
                        <EditPen />
                      </el-icon>审验
                    </span> -->
                    <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                      @confirm="deldetebm(row)" v-if="['21'].includes(zbbmzt) && row.isHadBtnAuth">
                      <template #reference>
                        <span class="operdel" size="small"><el-icon>
                            <Delete />
                          </el-icon>删除</span>
                      </template>
                    </el-popconfirm>
                    <span class="operesee" @click="handlepj(row, 'xq')"><el-icon>
                        <Compass />
                      </el-icon>详情</span>
                  </template>
                </el-table-column>
              </el-table>
              <div class="fenye" :style="{ top: tableHeight }">
                <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                  :current-page="listpage.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="listpage.pageSize"
                  layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
              </div>
            </div>

          </div>
        </div>
      </div>

    </div>
    <!-- 辨识-评价小组 -->
    <addPjxzTc ref="addPjxzTcRef" @ok="savebmyj" :planid="props.planid" />
    <!-- 选择人员 -->
    <ChooseUser v-model="chooseUserVisible" :deptId="deptId" :data="userids" :Single="singleShow" :leaderid="leaderid"
      @choosedUsers="getSonValue">
    </ChooseUser>
    <!-- 选择参与部门: -->
    <ChooseDept v-if="showJkssbm" :formInfo="fromObj" :showDdld="showJkssbm" :searchType="'03'" @closezzjg="closeJhss"
      @listdata="getSonValue" :zzlx="zzlx" />
    <!-- 评价 -->
    <div v-if="showpjpage" class="dialog-box">
      <pJindex @close="changepjclose" :idlist="idlist" :tjtype='tjtype' :deptcode='listpage.depcode' />
    </div>
    <userModel v-model:ids="auditForm.userId" tcTitle="选择审核人" :Single="true" v-model:cName="auditForm.founderName"
      width="300" ref="userModelRef" @change="userModelChange" />
    <!-- 评价小组成员分工清单 -->
    <listEvaluationteams v-if="activeTab === 'listEvaluationteams'" :planid="props.planid" :parentstatus="parentstatus"
      @close="Close">
    </listEvaluationteams>
  </div>
</template>
<script setup>
// 引入
import { defineProps, watch, onMounted, getCurrentInstance, defineEmits, ref, computed } from 'vue'
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import ChooseDept from "@/components/MyComponents/ChooseDept/Depart.vue";
import * as MOSTY from "@/components/MyComponents/index";
import pJindex from './pjindex.vue';
import { ElMessage } from "element-plus";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import addPjxzTc from './component/addPjxzTc.vue';
import { filterqx } from "@/utils/auth.js";// isSgs,isgs,isxgs,isaqbm,isldbz
import { getItem } from "@/utils/storage";
import userModel from './component/userModel.vue';
import listEvaluationteams from './listEvaluationteams.vue';
import { useRoute, useRouter } from "vue-router"
const route = useRoute()
const router = useRouter()
const emits = defineEmits(["close"]);
const { proxy } = getCurrentInstance();
const { GZ_D_ENT_STAGE } = proxy.$dict("GZ_D_ENT_STAGE");
/***是否安全部门 */
const isAqbm = filterqx('isaqbm') == '1'
/**登陆人id */
const USERID = getItem("USERID").toString()
const tableHeight = ref()
const showpjpage = ref(false)
const props = defineProps({
  btnshow: {
    default: true,
    type: Boolean
  },
  initPage: Object,
  title: String,
  planid: {
    type: String,
    default: null
  },
  rowstatus: {
    type: String,
    default: null
  }
});
const deptId = ref(null)
const tjtype = ref('pj')
const userids = ref([]);
const deptlist = ref([])
const showbtn = ref(false);
const ids = ref(null)
const shsm = ref(null)
/** 左边部门状态 */
const zbbmzt = ref(1)//左边部门状态
const total = ref(0)
const status = ref(2)
const zzlx = ref(null);
const showJkssbm = ref(false);//选择部门
const addPjxzTcRef = ref(null)
const proms = ref({
})
const listQuery = ref({})
const listpage = ref({
  pageCurrent: 1,
  pageSize: 10,
  planid: props.planid
})
/** 重大风险辨识遗漏驳回 组件 */
const userModelRef = ref()
const tableData1 = ref([])
const tableData2 = ref([])
const infoList = ref([])
const tableloading = ref(false)
const addyyShow = ref(false)
const chooseUserVisible = ref(false);
const leaderid = ref("");
const singleShow = ref(true); //单选多选
/** 权限对象 key userid, value: scope(部门范围)   */
const authObj = ref({})
const tableColumn = ref([
  {
    title: "分公司",
    prop: "entityName",
    sortable: true
  },
  {
    title: "风险数量",
    prop: "num",
    slot: true,
    sortable: true
  },
  {
    title: "状态",
    prop: "stage",
    sortable: true,
    slot: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const tableColumn2 = ref([
  {
    title: "分公司",
    prop: "entityName",
    sortable: true
  },

  {
    title: "评价人员",
    prop: "usernames",
    sortable: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const idlist = ref({
  planid: props.planid,
})
const auditForm = ref({
  userId: '',
});
const parentstatus = ref(null)
onMounted(() => {
  proms.value.planid = props.planid
  tabHeightFn();
  getpageDate()
  // setAuthObj()
})
//辨识评价-页面数据详情
function getpageDate() {
  // orgcode:只有评价小组登录才传orgcode
  getApi({ planid: props.planid }, '/mosty-jcgl/dangerPlanlist/bspj/showSjInfo').then(res => {
    tableData1.value = res.list
    let arr = tableData1.value.filter(item => {
      return (item.orangePointCount + item.redPointCount + item.yellowPointCount
        + item.bluePointCount) > 0
    })
    let arr2 = tableData1.value.filter(item => {
      return item.stage == '21'
    })



    if (arr.length > 0) {
      handlexg(arr[0])
    } else if (arr2.length > 0) {
      handlexg(arr2[0])
    }
    infoList.value = res.list.map(item => {
      return { entityCode: item.entityCode, entityName: item.entityName, id: item.id, usernames: item.teamUsernames, userids: item.teamUserids }
    })
    deptlist.value = res.list.map(item => {
      return { value: item.entityCode, label: item.entityName }
    })
    shsm.value = res.shsm ? res.shsm : null
    // status.value = res.entity.status
    listQuery.value = res.entity;
    proms.value.identifyEntityId = res.entity.id;
    idlist.value.identifyEntityId = res.entity.id;
    parentstatus.value = res.entity.stage
    //     10-部门辨识中
    // 20-分公司辨识中 21-分公司汇总评价中
    // 30-整体任务辨识中 31-省、市公司分管领导审核中 32- 省、市公司主管领导审核中  33-完成
    if (['30', '31', '32'].includes(res.entity.stage)) {
      status.value = 3
    } else if (res.entity.stage == '33') {
      status.value = 4
    }
  })
}
//修改评价小组
function changbs() {
  // showbtn.value = true
  // addyyShow.value = true
  addPjxzTcRef.value.open({ type: 'add' })
}
/** 重大风险驳回 */
const bigDangerReject = ({ }) => {
  const params = { identifyEntityId: proms.value.identifyEntityId }
  getApi(params, `/mosty-jcgl/dangerPlanlist/bspj/omitBackByMajor`).then(res => {
    ElMessage({
      type: 'success',
      message: '重大风险辨识遗漏驳回成功！',
    })
    getpageDate()
  })
}

//评价
function handlepj(row, type) {
  idlist.value = { ...row }
  idlist.value.bmbsid = row.id
  idlist.value.objid = row.objid
  tjtype.value = type
  showpjpage.value = true
}
//关闭汇总
function changepjclose(val) {
  showpjpage.value = false;
  listpage.value.depcode = val;
  getpageDate();
  getpjxqTab()
}
const getSonValue = (value) => {
  if (zzlx.value == '01') {
    infoList.value.forEach((el) => {
      if (el.id == ids.value) {
        el.usernames = value.map(it => { return it.userName }).toString();
        el.userids = value.map(it => { return it.id }).toString();
      }
    })
  }
};
//提交评价小组
function savebmyj() {
  // let arr = infoList.value.filter(it => {
  //   return it.userids
  // })
  // proms.value.infoList = infoList.value;
  // if (arr.length == infoList.value.length) {
  //   getSave(proms.value)
  // } else {
  //   // ElMessage.error("还有部门的评价人员未添加");

  // }
  // setAuthObj()
  getpjxqTab()
}

const userModelChange = (val) => {
  const params = {
    identifyEntityId: proms.value.identifyEntityId,
    userId: auditForm.value.userId
  }
  postApi(params, `/mosty-jcgl/dangerPlanlist/bspj/tjsh`).then(res => {
    ElMessage.success("提交成功");
    getpageDate();
    tableData2.value = []
  })
}
//提交审核（负责人提交审核）
function handlehz() {
  // 	辨识评价-各个市、省公司提交审核
  userModelRef.value.show(true)

  // postApi({}, `/mosty-jcgl/dangerPlanlist/bspj/tjsh/${proms.value.identifyEntityId}`).then(res => {
  //   ElMessage.success("提交成功");
  //   getpageDate();
  //   tableData2.value = []
  // })
}
//	辨识评价-添加、修改评价小组
function getSave(data) {
  postApi(data, '/mosty-jcgl/dangerPlanlist/bspj/addOrEditPjxz').then(res => {
    ElMessage.success("修改成功");
    addyyShow.value = false;
    getpageDate()
  })
}
const closeJhss = (val) => {
  showJkssbm.value = val
}
//取消人员修改
function xqproms() {
  addyyShow.value = false
  getpageDate()
}

//查看
function handlexg(row) {
  listpage.value.depcode = row.entityCode;
  zbbmzt.value = row.stage
  getpjxqTab()
  // if (['XGS','SZGS','SGS'].includes(props.initPage.type)) {
  //   listpage.value.depcode = row.entityCode;
  //   getpjxqTab()
  // }
  //  else {
  //   listpage.value.countycode = row.entityCode;
  //   listpage.value.spfag = row.spfag;
  //   getpjxqTab()
  // }

}

//   辨识评价 - 查询各个单位的辨识情况
function getpjxqTab() {
  tableData2.value = []
  getApi(listpage.value, '/mosty-jcgl/dangerPlanlist/bspj/getBmbsListByDeptId').then(async (res) => {
    total.value = res.total
    const results = []
    for (const item of res?.records) {

      try {
        let params = {
          // identifyOrgId: listpage.value.depcode,
          bmbsid: item.id,
        }
        const authRes = await getApi(params, '/mosty-jcgl/tbDangerIdentifyEvaluateMember/checkEvaluatePermission')
        results.push({
          ...item,
          isHadBtnAuth: authRes || false
        })
      } catch (error) {
        results.push({
          ...item,
          isHadBtnAuth: false
        })
      }
    }
    tableData2.value = results
  })
}
// 方法
const tabHeightFn = () => {
  tableHeight.value =
    window.innerHeight - 100 - 57 - 60 + 'px'
}
//删除
function deldetebm(row) {
  // 	部门汇总-部门辨识数据删除
  postApi({ bmbsid: row.id, identifyEntityId: proms.value.identifyEntityId }, '/mosty-jcgl/dangerPlanlist/hzDel').then(res => {
    ElMessage.success("删除成功");
    getpageDate()
    getpjxqTab()
  })
}
//返回
function Close() {
  emits("close");
}
//分页
const handleSizeChange = (currentSize) => {
  listpage.value.pageSize = currentSize;
  getpjxqTab()
};
const handleCurrentChange = (currentPage) => {
  listpage.value.pageCurrent = currentPage;
  getpjxqTab()
};
/**设置权限人员，-部门对象 */
const setAuthObj = (val) => {
  getApi({}, `/mosty-jcgl/dangerPjxz/getList?planId=${props.planid}`).then(res => {
    const arr = Array.isArray(res) ? res : []
    authObj.value = {}
    arr.forEach(item => {
      authObj.value[item.userId] = { scopeId: item.scopeId, id: item.id }
    })
  })
}
// const isHadBtnAuth = computed(() => {
//   /**当前用户  */
//   const userObj = authObj.value[USERID]
//   if (!userObj) return false
//   if (!userObj.scopeId) return true // 未设置即有权限
//   /**有权限的单位数组 */
//   const dwScopeArr = userObj.scopeId ? userObj.scopeId.split(',') : []
//   return dwScopeArr.indexOf(listpage.value.depcode) > -1
// })

const rowClick = (row, column, event) => {
  const countNum = row.orangePointCount + row.redPointCount + row.yellowPointCount + row.bluePointCount
  const isCanClick = row.stage == '21' || countNum > 0
  if (!isCanClick) return
  listpage.value.depcode = row.entityCode;
  zbbmzt.value = row.stage
  getpjxqTab()
}
const tabs = ref([{
  label: '评价小组成员分工清单',
  value: 'listEvaluationteams'
}, {
  label: '风险评价',
  value: 'bspjindex'
},
])
const activeTab = ref("listEvaluationteams")
const onTabClick = e => {
  const tabName = e.props.name
  activeTab.value = tabName
}

</script>

<style lang="scss" scoped>
@import "@/views/dutyBook/jgryandzz/talentPool/tabContainer.scss"; // 里面有 tab-container 样式
    .anquantr-container {
      background-color: #fff;
  
      .tab-container-scope {
        border-bottom: 1px solid #ebeef5;
      }
    }
  
    .titleBox {
      border: none;
      height: 152px;
      display: flex;
      justify-content: center;
      position: relative;
      z-index: 2;
    }
  
    .el-form-item__label {
      padding: 12px 12px 0 0 !important;
    }
  
    .stebox {
      width: 90%;
      display: flex;
      justify-content: center;
      position: relative;
      align-items: center;
      margin: o auto;
    }
  
    .left {
      width: 70%;
    }
  
    .el-select {
      width: 150px;
    }
  
    .btnBox {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin: 10px;
    }
  
    .bs-title {
      color: red;
      margin: 10px;
    }
  
    .leftbox {
      width: 30%;
      margin-right: 40px;
    }
  
    .tabBox2 {
      width: 65%;
    }
  
    .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;
    }
  
    .box-big {
      display: flex;
      margin-top: 10px;
  
      .fix-box {
        display: flex;
        margin-right: 30px;
      }
    }
  
    .el-textarea {
      --el-input-placeholder-color: #4c4e52 !important;
    }
  
    .btnpas {
      display: inline-block;
      padding: 5px 10px;
      color: #fff !important;
      margin-right: 4px;
      background-color: var(--el-color-primary);
      border-radius: 5px;
      cursor: pointer;
    }
  
    .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>
