<template>
  <div class="bigBox">
    <section v-show='props.isShowTotal' ref="getHeight">
      <XgfTotal :obj="pageData.listQuery" ref="aqqcTotal" :key="keys" />
    </section>
    <!-- 查询 -->
    <el-divider />
    <div class='tabox'>
      <section class="query-flex" ref="queryHeight">
        <section class="query-section">
          <section class="flex">
            <el-input placeholder="相关方名称" v-model="pageData.listQuery.relatedname" clearable
              style='width:250px'></el-input>
            <MOSTY.DictRidioAndSelect class="ml12" placeholder="请选择业务类型" style='width:250px' :dictData="D_TB_RELATED"
              v-model="pageData.listQuery.relatedtype" selectType="select" @getselect="handleSelectStatus" />
            <MOSTY.DictRidioAndSelect class="ml12" placeholder="请选择相关方类型" style='width:250px'
              :dictData="D_TB_RELATED_TYPE" v-model="pageData.listQuery.type" selectType="select"
              @getselect="handleSelectStatus" />
          </section>
        </section>
        <div class="query-btn">
          <el-button @click="gettablist" class="ml6">
            <el-icon>
              <Search />
            </el-icon>
            查询
          </el-button>
          <el-button @click="handleRest">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </div>
      </section>
      <el-divider />
      <section class="button">
        <el-button @click="addInfo(null, '01')">
          <!-- v-if='isAuth' -->
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
        <el-button @click="handleExport" v-loading="exportLoading" :disabled="pageData.tableData.length == 0">
          <el-icon>
            <Download />
          </el-icon>
          导出
        </el-button>
      </section>
      <section :style="{ 'height': totalHeight }">
        <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="pageData.tableData" :tableloading="tableloading"
          :isSelect="false" :isSort="false" @SortChange="SortChange" actionsW="280">
          <template #sign="{ row }">
            <p style=" width: 12px; height: 12px;border-radius: 50%;margin: 0 auto"
              :style="{ 'background-color': row?.sign ? '#33CC00' : '#FC5F76' }"></p>
          </template>
          <template #type="{ row }">
            <dict-tag :options="D_TB_RELATED_TYPE" :value="row.type" :tag="false" />
          </template>
          <template #contactsname="{ row }">
            <span v-if="row.contactsname">{{ row.contactsname }}</span>
            <span v-else-if="row.legalpersonphone">{{ row.relatedname }}</span>
            <span v-else>无</span>
          </template>
          <template #contactsphone="{ row }">
            <span v-if="row.contactsphone">{{ row.contactsphone }}</span>
            <span v-else-if="row.legalpersonphone">{{ row.legalpersonphone }}</span>
            <span v-else>无</span>
          </template>
          <template #relatedtype="{ row }">
            <dict-tag :options="D_TB_RELATED" :value="row.relatedtype" :tag="true" />
          </template>
          <template #signSecurityProtocol="{ row }">
            <dict-tag :options="D_BZ_SF" :value="row.signSecurityProtocol" :tag="false" />
          </template>
          <template #zzFlag="{ row }">
            <dict-tag :options="D_BZ_SF" :value="row.zzFlag" :tag="false" />
          </template>
          <template #residentStakeholders="{ row }">
            <dict-tag :options="D_BZ_SF" :value="row.residentStakeholders" :tag="false" />
          </template>
          <template #involveDanger="{ row }">
            <dict-tag :options="D_BZ_SF" :value="row.involveDanger" :tag="false" />
          </template>
          <template #status="{ row }">
            <dict-tag :options="D_BZ_HZZT" :value="row.status" :tag="false" />
          </template>
          <template #actions="{ row }">
            <section class="flexs">
              <span class="operedit flexs" @click="addInfo(row, '02')">
                <!-- v-if='isAuth' -->
                <el-icon>
                  <EditPen />
                </el-icon>编辑</span>
              <el-popconfirm v-if="row.responsibilitydeptid === deptId" confirm-button-text="是" cancel-button-text="否"
                icon-color="red" title="确定要删除?" @confirm="handledelete(row)">
                <!-- v-if='isAuth' -->
                <template #reference>
                  <span class="operdel flexs" size="small">
                    <el-icon>
                      <Delete />
                    </el-icon>删除</span>
                </template>
              </el-popconfirm>
              <span class="operesee flexs" @click="addInfo(row, '03')">
                <el-icon>
                  <View />
                </el-icon>查看</span>
              <el-popconfirm v-if='row.status == "1" && row.responsibilitydeptid === deptId' confirm-button-text="是"
                cancel-button-text="否" icon-color="red" title="确定要结束合作?" @confirm="changejshz(row, '2')">
                <!-- isAuth && -->
                <template #reference>
                  <span class="operedown flexs"><el-icon>
                      <Lock />
                    </el-icon>合作结束</span>
                </template>
              </el-popconfirm>
              <el-popconfirm v-if='row.status == "2" && row.responsibilitydeptid === deptId' confirm-button-text="是"
                cancel-button-text="否" icon-color="red" title="确定要开始合作?" @confirm="changejshz(row, '1')">
                <!-- isAuth && -->
                <template #reference>
                  <span class="operedown flexs"><el-icon>
                      <Lock />
                    </el-icon>开始合作</span>
                </template>
              </el-popconfirm>
            </section>
          </template>
        </MOSTY.Table>
      </section>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
          @changeSize="handleSizeChange" />
      </div>
    </div>
  </div>

</template>
<script setup>
import * as MOSTY from "@/components/MyComponents/index"
import { reactive, ref, onMounted, getCurrentInstance, watch, computed, nextTick } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { ElMessage, ElLoading } from "element-plus"
import { exportXlsx } from "@/excel/Export2Excel.js"
import { getAuth, singleObjectCheck } from "@/utils/tools.js"
import { getItem } from "@/utils/storage"
import XgfTotal from "./XgfTotal.vue"
const deptId = ref(getItem("deptId").ssbmid)
const { proxy } = getCurrentInstance()
const { D_TB_RELATED_TYPE, D_TB_RELATED, D_BZ_SF, D_BZ_HZZT, D_TB_RELATED_HZPC } = proxy.$dict(
  "D_TB_RELATED_TYPE", "D_TB_RELATED", "D_BZ_SF", "D_BZ_HZZT", "D_TB_RELATED_HZPC")
const emits = defineEmits(["handleChange", "searchChange", "changePage"])
const props = defineProps({
  obj: {
    default: null,
    type: Object
  },
  type: {
    default: "",
    type: String
  },
  tableHeight: {
    default: "40vh",
    type: String
  },
  isShowTotal: {
    type: Boolean,
    default: false
  }
})
const tableloading = ref(false)
const isAuth = ref(false)
const getHeight = ref(null)
const queryHeight = ref(null)
const aqqcTotal = ref(null)
const keys = ref(0)
const exportLoading = ref(false)
let personalMark = ["type", "relatedname", "relatedadd", "relatedtype", "orgid", "responsibilitypersonname", "businesslicense",
  "legalperson", "contactsname", "contactsphone", "signSecurityProtocol", "cooperationTime", "personNum", "residentStakeholders",
  "cooperationfrequency", "involveDanger", "zzFlag", "yyzzfile", "idcardfile"]
let individualLabel = ["type", "relatedname", "relatedadd", "relatedtype", "responsibilitydeptid", "responsibilitypersonname",
  "legalpersonphone", "idCard", "signSecurityProtocol", "cooperationTime", "personNum", "residentStakeholders", "cooperationfrequency",
  "involveDanger", "zzFlag"]
const pageData = reactive({
  listQuery: {
    relatedname: "",
    relatedtype: "",
    pageSize: 20,
    pageCurrent: 1
  },
  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1,
    total: 0
  },
  tableColumns: [
    {
      title: "标记",
      prop: "sign",
      sortable: false,
      fixed: "left",
      width: 80,

      slot: true
    },
    {
      title: "相关方名称",
      prop: "relatedname",
      width: 200,
      fixed: "left",
      sortable: true
    },
    {
      title: "相关方类型",
      prop: "type",
      slot: true,
      sortable: true
    },
    {
      title: "业务类型",
      prop: "relatedtype",
      slot: true,
      sortable: true

    },
    {
      title: "业务联系人",
      prop: "contactsname",
      slot: true,
      sortable: true

    },
    {
      title: "联系电话",
      prop: "contactsphone",
      slot: true,
      sortable: true
    },
    {
      title: "进场人数",
      prop: "personNum",
      sortable: true
    },
    {
      title: "合作开始时间",
      prop: "cooperationTime",
      sortable: true
    },
    {
      title: "合作结束时间",
      prop: "cooperationEndTime",
      sortable: true
    },
    {
      title: "是否签订安全协议",
      prop: "signSecurityProtocol",
      slot: true,
      sortable: true
    },
    {
      title: "是否具备相应资质",
      prop: "zzFlag",
      slot: true,
      sortable: true

    },
    {
      title: "是否常驻相关方",
      prop: "residentStakeholders",
      slot: true,
      sortable: true

    },
    {
      title: "是否涉及危险作业",
      prop: "involveDanger",
      slot: true,
      sortable: true

    },
    {
      title: "属地管理部门",
      prop: "belongDeptName",
      sortable: true
    },
    {
      title: "属地管理责任人",
      prop: "belongResponsibilityName",
      sortable: true
    },
    {
      title: "归口责任部门",
      prop: "responsibilitydeptname",
      sortable: true
    },
    {
      title: "归口责任人",
      prop: "responsibilitypersonname",
      sortable: true
    },
    {
      title: "状态",
      prop: "status",
      slot: true,
      sortable: true
    },
    {
      title: "操作",
      prop: "actions",
      fixed: "right",
      slot: true
    }
  ],
  tableData: []
})
const totalHeight = ref(null)
watch(() => props.isShowTotal, (val) => {
  nextTick(() => {
    if (val) {
      totalHeight.value = `calc(100vh - ${338 + queryHeight.value.offsetHeight + getHeight.value.offsetHeight}px)`
      return
    }
    totalHeight.value = `calc(100vh - 370px)`
  })
}, {
  deep: true,
  immediate: true
})
onMounted(() => {
  isAuthorize()
  nextTick(() => {
    totalHeight.value = `calc(100vh - ${338 + getHeight.value.offsetHeight + queryHeight.value.offsetHeight}px)`
  })
  watch(
    () => props.obj.orgid,
    (newValue) => {
      if (newValue) {
        pageData.listQuery.orgid = newValue
        gettablist()
      }

    },
    { deep: true, immediate: true }
  )
})
// 是否可以操作
const isAuthorize = async () => {
  isAuth.value = await getAuth()
}

// 导出
const handleExport = (code) => {
  const loading = ElLoading.service({
    lock: true,
    text: "导出中...",
    background: "rgba(0, 0, 0, 0.7)"
  })
  let title = {
    relatedname: "相关方名称",
    type: "相关方分类",
    relatedtype: "业务类型",
    contactsname: "业务联系人",
    contactsphone: "联系电话",
    contactsphone: "联系电话",
    personNum: "进场人数",
    cooperationTime: "开始合作时间",
    signSecurityProtocol: "是否签订安全协议",
    zzFlag: "是否具备相应资质",
    residentStakeholders: "是否常驻相关方",
    involveDanger: "是否涉及危险作业",
    responsibilitydeptname: "归口部门",
    responsibilitypersonname: "归口责任人",
    status: "状态"
  }
  const params = {
    pageCurrent: 1,
    pageSize: 10999,
    orgid: props.obj.orgid
  }
  postApi(params, "/mosty-jcgl/relatedpartyinfo/getPageList").then((res) => {
    if (res.records) {
      let data = res.records
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].type = proxy.$getDictVal(data[i].type, D_TB_RELATED_TYPE)
          data[i].relatedtype = proxy.$getDictVal(data[i].relatedtype, D_TB_RELATED)
          data[i].signSecurityProtocol = proxy.$getDictVal(data[i].signSecurityProtocol, D_BZ_SF)
          data[i].zzFlag = proxy.$getDictVal(data[i].zzFlag, D_BZ_SF)
          data[i].residentStakeholders = proxy.$getDictVal(data[i].residentStakeholders, D_BZ_SF)
          data[i].involveDanger = proxy.$getDictVal(data[i].involveDanger, D_BZ_SF)
          data[i].status = proxy.$getDictVal(data[i].status, D_BZ_HZZT)
        }
        let tablename = "相关方信息列表.xlsx"
        exportXlsx(title, data, "相关方信息列表", tablename)
      }
    }
  }).finally(() => {
    loading.close()
  })
}
// 重置过滤条件
const handleRest = () => {
  pageData.listQuery.relatedname = ""
  pageData.listQuery.relatedtype = ""
  pageData.listQuery.type = ""
  pageData.pageConfiger.pageCurrent = 1
  pageData.listQuery.pageCurrent = 1
  gettablist()
}

//排序
function SortChange(prop, order) {
  pageData.listQuery.sortField = prop
  pageData.listQuery.sortOrder = order
  gettablist()
}

function gettablist() {
  tableloading.value = true
  postApi(pageData.listQuery, "/mosty-jcgl/relatedpartyinfo/getPageList").then(async (res) => {
    if (res) {

      keys.value++
      let res_data = []
      // pageData.tableData = res.records
      for (let i = 0; i < res.records.length; i++) {
        res.records[i].type === "02" ?
          res_data.push(await singleObjectCheck(res.records[i], individualLabel)) :
          res_data.push(await singleObjectCheck(res.records[i], personalMark))
      }
      pageData.tableData = res_data
      console.log("页面数据")
      console.log(pageData.tableData)
      pageData.tableData.forEach(item => {
        item.relatedtype = item.relatedtype ? item.relatedtype.split(",") : []
      })
      pageData.pageConfiger.total = res.total
    }
  }).finally(() => {
    tableloading.value = false
  })
}

//新增
const addInfo = (row, type) => {
  let arr = {
    id: row && row.id ? row.id : null,
    orgid: row && row.orgid ? row.orgid : null,
    zdlist: { D_TB_RELATED_TYPE, D_TB_RELATED, D_BZ_SF, D_BZ_HZZT, D_TB_RELATED_HZPC }
  }
  if (type == "02") {
    arr.saveBtnShow = true
    arr.avtivityBtnShow = true
    arr.title = "相关方编辑"
  } else if (type == "03") {
    arr.saveBtnShow = false
    arr.avtivityBtnShow = false
    arr.title = "相关方详情"
  } else {
    arr.saveBtnShow = true
    arr.title = "相关方新增"
  }
  emits("changePage", "Details", arr)
}

//注销
function handledelete(row) {
  postApi({}, `/mosty-jcgl/relatedpartyinfo/delete/${row.id}`).then(res => {
    ElMessage.success("删除成功")
    gettablist()
  })
}

//结束合作
function changejshz(row, status) {
  postApi({ id: row.id, status }, "/mosty-jcgl/relatedpartyinfo/changeCooperation").then(res => {
    ElMessage.success("提交成功")
    gettablist()
  })
}

//页码发生变化
const handleCurrentChange = (val) => {
  pageData.pageConfiger.pageCurrent = val
  pageData.listQuery.pageCurrent = val
  gettablist()
}
//查询条数发生变化
const handleSizeChange = (val) => {
  pageData.pageConfiger.pageSize = val
  pageData.listQuery.pageSize = val
  gettablist()
}
</script>

<style lang="scss" scoped>
::v-deep .el-divider--horizontal {
  margin: 12px 0;
}

.query-flex {
  display: flex;
  justify-content: space-between;

  .query-section {
    width: 68%;
  }

  .query-btn {
    width: 240px;
    display: flex;
    justify-content: flex-end;

    .toggle {
      height: 32px;
      cursor: pointer;
      display: flex;
      align-items: center;
      color: #0f3916;

      .el-icon {
        transform: rotate(90deg);
        transition: all 0.25s ease;
      }

      &.active {
        .el-icon {
          transform: rotate(-90deg);
        }
      }
    }
  }
}

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

.flexs {
  display: flex;
  align-items: center;
  justify-content: space-around;
}
</style>
