<template>
  <div class="bigBox">
    <!-- <section v-show="props.isShowTotal" ref="getHeight">
      <Total :obj="fromObj" ref="aqqcTotal" />
    </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.keywords" clearable
              style="width: 250px"></el-input>
            <el-date-picker class="ml12" v-model="pageData.listQuery.time" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            <el-input class="ml12" placeholder="请输入单位查询" v-model="pageData.listQuery.orgName" clearable
              style="width: 250px"></el-input>
          </section>
        </section>
        <div class="query-btn">
          <el-button @click="queryData" 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="handleMaskData('add', '新增', '')" v-if="isAqbm">
          <el-icon>
            <Plus />
          </el-icon>新增</el-button>
      </section>
      <section :style="{ height: totalHeight }">
        <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="pageData.tableData" :tableloading="tableloading"
          :isSelect="true" :isSort="true" actionsW="280">
          <template #state="{ row }">
            <el-tag v-if="row.state == '00'" type="info">未上报</el-tag>
            <el-tag v-if="row.state == '01'" type="warning">待审批</el-tag>
            <el-tag v-else-if="row.state == '02'" type="success">已发布</el-tag>
            <el-tag v-else-if="row.state == '03'" type="danger">未通过</el-tag>
          </template>
          <template #reportType="{ row }">
            <el-tag :type="colorTypeObj[row.reportType]">{{ D_BZ_DXAL_OBJ[row.reportType] }}</el-tag>
          </template>
          <template #actions="{ row }">
            <span v-if="isShowEditBtn(row)" class="operedit" @click="handleMaskData('edit', '编辑', row.id, row)">
              <el-icon>
                <EditPen />
              </el-icon>编辑</span>

            <el-popconfirm v-if="isShowDelBtn(row)" confirm-button-text="是" cancel-button-text="否" icon-color="red"
              title="确定要删除?" @confirm="handleDelete(row)">
              <template #reference>
                <span class="operdel" size="small">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除</span>
              </template>
            </el-popconfirm>
            <el-popconfirm confirm-button-text="是" v-if="isShowReportBtn(row)" cancel-button-text="否" icon-color="red"
              title="确定要上报?" @confirm="handlePush(row)">
              <template #reference>
                <span class="operedit" size="small">
                  <el-icon>
                    <Upload />
                  </el-icon>
                  上报</span>
              </template>
            </el-popconfirm>
            <span class="operesee" @click="handleMaskData('view', '查看', row.id, row)">
              <el-icon>
                <View />
              </el-icon>查看</span>
          </template>
        </MOSTY.Table>
      </section>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
          @changeSize="handleSizeChange" />
      </div>
    </div>
  </div>
  <!-- 典型案例 -->
  <div v-if="aqqcShow" class="dialog-box">
    <Detail :title="title" :type="type" @close="handleClose" :id="detailId" :currRow="currRow" />
  </div>
</template>
<script setup>
import * as MOSTY from "@/components/MyComponents/index"
import Detail from "./Detail.vue"
import { reactive, ref, onMounted, watch, nextTick, computed, getCurrentInstance } from "vue"
import { filterqx } from "@/utils/auth.js"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { ElMessage } from "element-plus"
import { getItem } from "@/utils/storage"
import Total from "./Total.vue"
import { useRoute, useRouter } from "vue-router"
import { htmlToText } from '@/utils/tools.js'

const { proxy } = getCurrentInstance()
const { D_BZ_DXAL } = proxy.$dict("D_BZ_DXAL")

const props = defineProps({
  isShowTotal: {
    type: Boolean,
    default: false
  }
})
const route = useRoute()
const router = useRouter()

const tableloading = ref(false)
/** 当前行 */
const currRow = ref({})
const aqqcShow = ref(false)
const getHeight = ref(null)
const queryHeight = ref(null)
const aqqcTotal = ref(null)
const detailId = ref("")
const title = ref("")
const type = ref("")
const pageData = reactive({
  listQuery: {
    keywords: "",
    // orgId: "",
    time: []
  },
  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1,
    total: 0
  },
  tableColumns: [

    {
      title: "案例名称",
      prop: "title"
    },
    {
      title: "案例内容",
      prop: "contentText",
    },
    {
      title: "添加人",
      prop: "publisher"
    },
    {
      title: "案例时间",
      prop: "caseTime"
    },
    {
      title: "发布时间",
      prop: "issuedTime"
    },

    // {
    //   title: "状态",
    //   prop: "state",
    //   slot: true
    // },
    {
      title: "上报状态",
      prop: "reportType",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  tableData: []
})
const fromObj = ref({})
const totalHeight = ref(null)
// 推送状态
const D_BZ_DXAL_OBJ = computed(() => {
  if (!D_BZ_DXAL.value?.length) return {}
  let obj = {}
  D_BZ_DXAL.value.forEach(item => {
    obj[item.value] = item.label
  })
  return obj
})
/** 审核对照对象 00：待上报01：市审核中 02：省审核中 03：市审核完成 04：省审核完成 05：市审核未通过 06：省审核未通过(字典可能会变化，目前如此) */
const colorTypeObj = {
  "00": "",
  "01": "warning",
  "02": "warning",
  "03": "success",
  "04": "success",
  "05": "danger",
  "06": "danger"
}
// 是否是安全部门
const isAqbm = computed(() => {
  return filterqx("isaqbm") == "1"
})
// 是否是省账号 且安全部门
const isProvinces = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isSgs") == "1"
})
/** 是否是省账号 */
const isProvinceTrue = computed(() => {
  return filterqx("isSgs") == "1"
})
// 是否是本单位数据
const isDwData = _id => {
  return getItem("deptId").ssdwid == _id
}
watch(
  () => props.isShowTotal,
  val => {
    nextTick(() => {
      // if (val) {
      //   totalHeight.value = `calc(100vh - ${340 + queryHeight.value.offsetHeight + getHeight.value.offsetHeight}px)`
      //   return
      // }
      totalHeight.value = `calc(100vh - 372px)`
    })
  },
  {
    deep: true,
    immediate: true
  }
)
onMounted(() => {
  queryData()
  nextTick(() => {
    totalHeight.value = `calc(100vh - 372px)`
    // totalHeight.value = `calc(100vh - ${340 + getHeight.value.offsetHeight + queryHeight.value.offsetHeight}px)`
  })
  if (route.query.id) goToAudit(route.query)
})
const isShowEditBtn = row => {

  if (row.state == '01') return false
}
const isShowDelBtn = row => {

  if (row.state == '01') return false
}
// 关闭弹窗
const handleClose = val => {
  aqqcShow.value = false
  if (val) {
    queryData()
  }
  if (route.query.id) router.replace({ path: '/dutyBook/dianXal/index' })
}
// 重置过滤条件
const handleRest = () => {
  Object.assign(pageData.listQuery, {
    keywords: "",
    // orgId: "",
    // orgName: "",
    time: []
  })
  // pageData.listQuery.orgName
  pageData.pageConfiger.pageCurrent = 1
  queryData()
}
//列表查询
function queryData() {
  tableloading.value = true
  postApi({ ...pageData.pageConfiger, ...pageData.listQuery }, "/mosty-jcgl/typicalCases/queryTypicalCases")
    .then(res => {
      if (res) {
        res.records = Array.isArray(res.records) ? res.records : []
        pageData.tableData = res.records.map(item => {
          item.contentText = htmlToText(item.content)
          return item
        })

        pageData.pageConfiger.total = res.total
      }
    })
    .finally(() => {
      tableloading.value = false
    })
}
//新增 修改 详情 审核
const handleMaskData = (val, _title, _id, row) => {
  detailId.value = _id
  type.value = val
  title.value = "典型案例" + _title
  currRow.value = row
  aqqcShow.value = true // 展示内容
}
const isShowReportBtn = row => {
  /** @type {String} - reportType 流程状态 00-未上报 01-市审核中 02-省审核中 03-市审核通过 04-省审核通过 05-市审核未通过 06-省审核未通过") */
  const reportType = row.reportType
  /** @type {String} 10 省 20 市 30 县*/
  const level = row.level
  /** @type {String} "状态", "00 未上报 01 待审批 02 已发布 03 未通过"*/
  const state = row.state
  if (!['00', '02', '03'].includes(state)) return false
  if (filterqx("isaqbm") != "1") return false
  // 省
  if (filterqx("isSgs") == "1") {
    return false

    // 市
  } else if (filterqx("isgs") == "1") {
    return level == '20' && ['00', '03', '06'].includes(reportType) // 市级(20)，且

    // 县
  } else {
    return level == '30' && ['00', '05'].includes(reportType)
  }
}
/**推送 */
const handlePush = row => {
  getApi({ id: row.id }, `/mosty-jcgl/typicalCases/reporting`).then(() => {
    ElMessage.success("上报成功")
    queryData()
  })
}
//删除
const handleDelete = row => {
  postApi([row.id], `/mosty-jcgl/typicalCases/delTypicalCases`).then(() => {
    ElMessage.success("删除成功")
    queryData()
  })
}
//页码发生变化
const handleCurrentChange = val => {
  pageData.pageConfiger.pageCurrent = val
  if (isAqbm.value) {
    queryData()
  }
}
//查询条数发生变化
const handleSizeChange = val => {
  pageData.pageConfiger.pageSize = val
  if (isAqbm.value) {
    queryData()
  }
}
/** 跳转审核详情 */
function goToAudit(query) {
  handleMaskData("approve", "审批", query.id)
}
</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: 250px;
    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;
}
</style>
