<template>
  <div class="box" v-if="props.isOpen">
    <div class="topper">
      <div class="sub-le">
        <div class="title">专职驾驶员</div>
        <!-- <BaseTag :items="practitioners" :num="3" /> -->
      </div>
    </div>
  </div>
  <div class="bottom">
    <TimeCondition :popover="popover" :ywId="props.id" @change="timeCondition" :title="title">
      <template #right>
        <el-popconfirm confirm-button-text="是" cancel-button-text="否" v-if="isProvinces" icon-color="red"
          title="若更新数据将重置，是否确认更新?" @confirm="manualUpdate">
          <template #reference>
            <el-button type="primary" class="mr5" :loading="permisssion.manualUpdate.loading"
              :disabled="permisssion.manualUpdate.disabled">手动更新</el-button>
          </template>
        </el-popconfirm>
        <el-popconfirm confirm-button-text="是" v-if="!isProvinces || isProvincesXN" cancel-button-text="否"
          icon-color="red" title="是否确认撤销?" @confirm="onRevoke(query.orgCode)">
          <template #reference>
            <el-button type="primary" class="mr5" :disabled="permisssion.revoke.disabled">撤销</el-button>
          </template>
        </el-popconfirm>
        <el-popconfirm v-if="isProvincesXN" confirm-button-text="是" cancel-button-text="否" icon-color="red"
          :title="`是否确认上报?`" @confirm="onReport">
          <template #reference>
            <el-button type="primary" class="mr5" :disabled="permisssion.report.disabled">上报</el-button>
          </template>
        </el-popconfirm>
        <el-popconfirm v-else confirm-button-text="是" cancel-button-text="否" icon-color="red"
          :title="`是否确认${isProvinces && permisssion.report.count > 0 ? '修改' : ''}上报?`" @confirm="onReport">
          <template #reference>
            <el-button type="primary" class="mr5" :disabled="permisssion.report.disabled">{{ isProvinces &&
              permisssion.report.count > 0 ? "修改" : !isProvinces ? "" : "首次" }}上报</el-button>
          </template>
        </el-popconfirm>
        <el-button type="primary" style="margin-left: 5px !important;" @click="reportResult(true)"
          :loading='loadingcksbjg' v-if="IsCksbjg">查看上报结果</el-button>
        <el-button type="primary" style="margin:0px 5px !important;" @click="handleExport">导出</el-button>

      </template>
    </TimeCondition>
    <el-table border :data="tableData" :height="`calc(100vh - ${props.isOpen ? 655 : 380}px)`" v-loading="tableLoading"
      :header-cell-style="{ background: '#F6F6F6' }" :cell-style="cellStyle" style="width: 99%;">
      <el-table-column type="selection" width="55" :selectable="onSelectable" />
      <el-table-column :label="item.label" :prop="item.prop" :fixed="item?.fixed" v-for="(item, index) in tableColumn"
        :key="index">
        <template #default="{ row }" v-if="item.prop == 'status'">
          <span v-if="row.status == '1'" style="color: green">已上报</span>
          <span v-else-if="row.status == '2'" style="color: red">未上报</span>
          <span v-else-if="row.status == '3'" style="color: #999">未查到数据</span>
          <span v-else-if="row.status == '4'" style="color: green">已上报到省公司</span>
          <span v-else-if="row.status == '5'" style="color: orange">正在上报国家局</span>
          <span v-else-if="row.status == '6'" style="color: green">已上报到国家局</span>
        </template>
        <template #default="{ row }" v-if="item.prop === 'count'">
          <span>{{ Number(row.registeredNum || 0) + Number(row.dispatchNum || 0) + Number(row.outsourceNum || 0)
            }}</span>
        </template>
        <template #default="{ row }" v-if="item.prop == 'wsbNum'">
          <span v-if="row.wsbNum == 0">0</span>
          <span v-else-if="row.wsbNum > 0" style="color: red; cursor: pointer" @click="onView(row, '2')">{{ row.wsbNum
            }}</span>
        </template>
        <template #default="{ row }" v-if="item.prop == 'sbcs'">
          <span v-if="row.sbcs == 0">0</span>
          <el-link v-else-if="row.sbcs > 0" type="primary" @click="onCount(row)">{{ row.sbcs }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="170" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" @click="onView(row, '')">查看</el-link>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="若更新数据将重置，是否确认更新?"
            @confirm="rowUpdate(row.orgCode)">
            <template #reference>
              <el-link type="primary" :disabled="setUpdate(row)">更新</el-link>
            </template>
          </el-popconfirm>
          <!-- <el-link disabled v-else>更新</el-link> -->
          <el-popconfirm confirm-button-text="是" v-if="!setPeject(row.status) && !isTown" cancel-button-text="否"
            icon-color="red" title="是否确认驳回?" @confirm="onRevoke(row.orgCode)">
            <template #reference>
              <el-link type="primary">驳回</el-link>
            </template>
          </el-popconfirm>
          <el-link disabled v-else>驳回</el-link>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-dialog v-model="dialogsbyy" :title="reportResultInfo?.dataname + '上报结果'" width="800px">
    <section v-if="reportResultInfo?.returnCode == '200' && !reportResultInfo.returnHttpCode">
      <section>上报人：{{ reportResultInfo.username }}</section>
      <section>上报时间：{{ reportResultInfo.sbsj }}</section>
      <section>上报结果：未出上报结果，请等待上报结果</section>
    </section>
    <section v-else-if="reportResultInfo?.returnCode !== '200' && !reportResultInfo.returnHttpCode">
      <section>上报人：{{ reportResultInfo.username }}</section>
      <section>上报时间：{{ reportResultInfo.sbsj }}</section>
      <section>上报结果：{{ reportResultInfo.returnMsg }}</section>
    </section>
    <section v-else-if="reportResultInfo?.returnCode == '200' && reportResultInfo?.returnHttpCode == '200'">
      <section>上报人：{{ reportResultInfo.username }}</section>
      <section>上报时间：{{ reportResultInfo.sbsj }}</section>
      <section>上报结果：上报成功</section>
    </section>
    <section v-else-if="reportResultInfo?.returnCode == '200' && reportResultInfo?.returnHttpCode != '200'">
      <section>上报人：{{ reportResultInfo.username }}</section>
      <section>上报时间：{{ reportResultInfo.sbsj }}</section>
      <section>上报结果：{{ reportResultInfo?.returnOperationResult }}</section>
    </section>
  </el-dialog>
  <DialogTableJsy :title="dialogTitle" @close="dialogClose" :orgCode="currId" :params="query"
    :reportStatus="reportStatus" :rowItem="rowItem" v-if="dialogVisible" />
  <ReportHistory :params="historyParams" v-if="reportHistoryVisible" @close="reportHistoryClose" />
</template>

<script setup>
import { ref, reactive, computed, watch, onBeforeUnmount } from "vue"
import TimeCondition from "@/views/dataReportWork/components/TimeCondition"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { getItem } from "@/utils/storage"
import { filterqx } from "@/utils/auth.js"
import DialogTableJsy from "../components/tab1/DialogTableJsy.vue"
import ReportHistory from "../components/tab1/ReportHistory.vue"
import { ElMessage, ElLoading } from "element-plus"
import { zzjsyXlsx } from "./tabtool";
const props = defineProps({ isOpen: Boolean, id: String, orgCode: String, dict: Object })
const currentCode = getItem("deptId").ssdwid
const tableColumn = ref([
  { label: '企业名称', prop: 'orgName', fixed: 'left' },
  { label: '总数（个）', prop: 'count' },
  { label: '在册在岗员工数量', prop: 'registeredNum' },
  { label: '劳务派遣员工数量', prop: 'dispatchNum' },
  { label: '业务外包数量', prop: 'outsourceNum' },
  { label: '未上报总数', prop: 'wsbNum' },
  { label: '最后一次上报时间', prop: 'updateTime', fixed: 'right' },
  { label: '当前上报状态', prop: 'status', fixed: 'right' },
  { label: '累计上报次数', prop: 'sbcs', fixed: 'right' },

])
const permisssion = reactive({
  manualUpdate: {
    //手动更新
    loading: false,
    disabled: false
  },
  report: {
    //上报
    count: 0,
    disabled: true
  },
  revoke: {
    //撤销
    disabled: true
  }
})
const isReportResult = ref(false)
const dialogsbyy = ref(false)
const IsCksbjg = ref(false)
const loadingcksbjg = ref(false)
const reportResultInfo = ref({})
const isAutoReport = ref(false)
const timer = ref(null)
// 是否是省账号
const isProvinces = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isSgs") == "1"
})
// 是否是省账号 并且时省本级
const isProvincesXN = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isSgs") == "1" && props.orgCode.includes('XN')
})
// 是否是市账号
const isCity = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") == "1"
})
//县级账号
const isTown = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") != "1" && filterqx("isSgs") != "1"
})
const query = reactive({
  orgCode: currentCode,
  year: "",
  jd: ""
})
const reportStatus = ref("")
const rowItem = ref(null)
const tableLoading = ref(false)
const tableData = ref([])
const dialogTitle = ref("")
const title = ref("专职驾驶员")
const popover = reactive({
  title: title.value,
  content: `
填表说明：
1. 填写单位：省级单位名称；
2. 企业名称：各省级单位机关或下属单位名称；
3. 统计频次：季度；
4. 提交周期：
● 第一季度：1月1日-4月5日
● 第二季度：4月1日-7月5日
● 第三季度：7月1日-10月10日
● 第四季度：10月1日-12月25日
5. 若没有驾驶员信息， 可不填写数据 ；但在周期对应的提交时间范围内仍需处长账号进行“上报确认”操作。
6. 相同专职驾驶员信息不可重复填报。
7. 专职驾驶员：
（1）准驾车型代号： 分为A1、A2、A3、B1、B2、C1、C2、C3；
注意： 若同一人存在多个准驾车型，按高的填报，如果是平级，请按实际驾驶车辆型号为准。
（2）人员类别：在册在岗人员、劳务派遣和业务外包人员；
注意：业务外包人员特指：驾驶我方车辆的专职驾驶员。
（3）违章情况：统计范围是车管部门发布的因公用车违章行为数据；
（4）违章类型：超载、超速、违章停车、违规变道、闯红灯、未系安全带、
操作不当、打手机、吸烟、疲劳驾驶、占用应急车道、其他；
（5）违章次数：填写本年度截止到当前统计周期的累计违章次数。
  `
})
const currId = ref(null)
const isSfsb = ref(false)
const dialogVisible = ref(false)
const reportHistoryVisible = ref(false)
const historyParams = ref(null)
onBeforeUnmount(() => {
  if (timer.value) {
    window.clearInterval(timer.value);
    timer.value = null;
  }
})
// 查看省局上报结果
const reportResult = (val) => {
  loadingcksbjg.value = true
  getApi({ year: query.year, id: props.id, jtsj: query.jd }, "/mosty-jcgl/dataCommon/getSbjg").then((res) => {
    if (res) {
      reportResultInfo.value = res
      if (val) {
        dialogsbyy.value = true
      }
      if (res.returnCode == "200" && !res.returnHttpCode) {
        isReportResult.value = true;
      } else {
        if (isAutoReport.value) {
          getPageData()
        }
        if (timer.value) {
          isAutoReport.value = false
        }
        window.clearInterval(timer.value);
        timer.value = null
      }
      if (res.returnCode == "200" && res.returnHttpCode == '500') {
        let res = getApi({ dataId: props.id }, "/mosty-jcgl/dataCommon/goBackData")
        if (res) {
          getPageData(false)
        }
      }
      // 只针对是否展示查看上报结果
      if (res.returnCode || res.returnHttpCode) {
        IsCksbjg.value = true

      } else {
        IsCksbjg.value = false
      }
    }
  }).finally(() => {
    loadingcksbjg.value = false
  });
};

//详情
function onView(row, type) {
  dialogVisible.value = true
  isSfsb.value = row.sfsb == "1" ? true : false
  reportStatus.value = type
  rowItem.value = row
  currId.value = row.orgCode
  dialogTitle.value = `专职驾驶员列表（${row.orgName}）`
}
const onCount = e => {
  reportHistoryVisible.value = true
  historyParams.value = {
    orgCode: e.orgCode,
    sbcs: e.sbcs,
    year: query.year,
    jd: query.jd
  }
}
const dialogClose = val => {
  dialogVisible.value = false
  if (val) {
    getPageData()
  }
}
const reportHistoryClose = val => {
  reportHistoryVisible.value = false
  if (val) {
    getPageData()
  }
}
const timeCondition = val => {
  query.year = val.yearValue
  query.jd = val.quarterValue
  if (props.orgCode) getPageData()
}
const manualUpdate = () => {
  permisssion.manualUpdate.loading = true
  tableLoading.value = true
  setTimeout(() => {
    // ElMessage({
    //   message: "更新成功",
    //   type: "success"
    // })
    // permisssion.manualUpdate.loading = false
  }, 1e3)
  // return;
  getApi({}, `/mosty-jcgl/data/riskUnit/manualUpdate`)
    .then(res => {
      getPageData()
      ElMessage({
        message: "更新成功",
        type: "success"
      })
      permisssion.manualUpdate.loading = false
    })
    .finally(() => {
      tableLoading.value = false
      permisssion.manualUpdate.loading = false
    })
}
const rowUpdate = code => {
  const loading = ElLoading.service({
    lock: true,
    text: '更新中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi({ orgCode: code }, `/mosty-jcgl/data/driver/syncLocal`)
    .then(() => {
      getPageData()
      ElMessage({
        message: "更新成功",
        type: "success"
      })
    }).finally(() => {
      loading.close()
    })
}
const getPageData = (val = true) => {
  tableLoading.value = true
  tableData.value = []
  postApi(query, "/mosty-jcgl/data/driverStat/queryDriverStat").then(res => {
    if (res) {
      if (res.length == 1 && res[0].status == '2') {
        permisssion.report.disabled = true
      }
      tableData.value = res
      tableLoading.value = false
      setPermisssion()
      if (val && res[0].status == '5') {
        // if (isReportResult.value) {
        timer.value = window.setInterval(() => {
          if (!isReportResult.value) {
            window.clearInterval(timer.value);
            timer.value = null;
            isAutoReport.value = false
          }
          reportResult();
        }, 1e4);
        // }
      } else {
        window.clearInterval(timer.value);
        timer.value = null
      }
    }
  })
    .catch(err => {
      tableLoading.value = false
    })
}
const onSelectable = row => {
  return true
}
const restPermisssion = () => {
  permisssion.manualUpdate.disabled = false
  permisssion.report.disabled = true
  permisssion.revoke.disabled = true
}
const getRevoke = async () => {
  let res = await postApi(query, `/mosty-jcgl/data/driverStat/isRevokedFlag`)
  permisssion.revoke.disabled = res ? false : true
}
const setPermisssion = async () => {
  const currentDate = new Date()
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth()

  restPermisssion()
  if (query.year != currentYear || query.jd != Math.floor(currentMonth / 3) + 1) return
  let res = await getApi({ id: props.id }, "/mosty-jcgl/dataCommon/sfQggzr")
  if (!res) {
    permisssion.manualUpdate.disabled = false //这里暂时打开手动更新按钮
    return
  }
  getRevoke()
  let count = 0
  tableData.value.forEach(item => {
    if (item.sbcs * 1 > 0) permisssion.report.count = item.sbcs * 1
    let onTown = () => {
      if (item.status == "2" || item.status == "3") permisssion.report.disabled = false
    }
    if (isTown.value) {
      onTown()
    }
    if (isCity.value) {
      if (query.orgCode.includes(currentCode) && query.orgCode.includes("XN")) {
        //本级
        onTown()
      } else if (query.orgCode === currentCode) {
        //市
        if (["1", "3", "4"].includes(item.status)) count++
        if (count > 0 && count === tableData.value.length) permisssion.report.disabled = false
      } else {
        //其他
      }
    }
    if (isProvinces.value) {
      if (query.orgCode.includes(currentCode) && query.orgCode.includes("XN")) {
        //省级
        onTown()
      } else if (query.orgCode === currentCode) {
        //省
        if (["1", "4", "6"].includes(item.status)) count++
        if (count > 0 && count === tableData.value.length) permisssion.report.disabled = false
      } else {
        //其他
      }
    }
  })
}
const setPeject = status => {
  if (isCity.value) {
    return ["1"].includes(status) ? false : true
  }
  if (isProvinces.value) {
    return ["1", "4", "6"].includes(status) ? false : true
  }
}
const setUpdate = row => {
  if (isTown.value) {
    return row.updateStatus === 1 ? false : true
  }
  if (isCity.value) {
    return row.updateStatus === 1 && ["2", "3"].includes(row.status) ? false : true
  }

  if (isProvinces.value) {
    if (query.orgCode.includes(currentCode) && query.orgCode.includes("XN")) {
      return row.updateStatus === 1 ? false : true
    } else return true
  }
}
const onRevoke = async code => {
  let params = JSON.parse(JSON.stringify(query))
  params.orgCode = code
  let res = await postApi(params, "/mosty-jcgl/data/driverStat/revokeData")
  if (res) {
    ElMessage({
      message: `${code === currentCode ? "撤销" : "驳回"}成功`,
      type: "success"
    })
    getPageData()
  }
}
const onReport = async () => {
  try {
    let res = await postApi(query, "/mosty-jcgl/data/driverStat/reportData")
    if (res) {
      ElMessage({
        message: "上报成功",
        type: "success"
      })
      isAutoReport.value = true
      getPageData()
    }
  } catch (error) {
    ElMessage({
      message: '上报失败',
      type: "error"
    })
  }
}
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if ([2, 3, 4].includes(columnIndex)) {
    return { background: "rgb(240,249,235) !important" }
  }
  if (columnIndex === 5) {
    return { background: "var(--el-color-primary-light-8)!important" }
  }
}

watch(
  () => props.orgCode,
  (n, o) => {
    if (n && query.year) {
      query.orgCode = n
      getPageData()
    }
  }
)
defineExpose({ getPageData })
const handleExport = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi(query, '/mosty-jcgl/data/export/driver').then(res => {

    zzjsyXlsx(res ? res : [], props.dict, popover.content)

  }).finally(() => {
    loading.close()
  })
}
</script>

<style lang="scss" scoped>
::v-deep .el-link {
  border: none;
  background: none;
  color: var(--el-color-primary);
  padding: 0;
  margin-left: 10px !important;

  &:hover,
  &:focus {
    background: none;
    border: none;
    opacity: 0.9;
  }
}

::v-deep .el-button--link.is-disabled,
::v-deep.el-link.el-link--primary.is-disabled {
  color: #808596;
  border: none;
  background: none;
}

::v-deep .el-link.is-disabled {
  cursor: no-drop;
}

.content {
  .topper {
    display: flex;
    margin-bottom: 10px;

    .sub-le {
      width: 710px;
      padding: 15px 15px 5px 15px;
    }
  }

  .bottom {
    padding: 15px 15px 5px 15px;
  }

  .leceri {
    display: flex;

    .le,
    .ri {
      flex: 1;
    }

    .ce {
      padding: 6px 0;

      .ince {
        width: 36px;
        padding-left: 10px;
        background: #eef6f6;
        height: 100%;
        margin: 0 3px;
      }
    }
  }

  .subs {
    display: flex;
    padding-top: 6px;

    .sub-le {
      flex: 1;
    }

    .sub-ri {
      width: 450px;

      ::v-deep .item {
        padding: 0 3px;

        .inner {
          height: 103px;
          padding-top: 26px;
        }
      }
    }
  }
}
</style>
