<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-date-picker class="ml12" v-model="pageData.listQuery.time" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            <MOSTY.DictRidioAndSelect class="ml12" :dictData="D_BZ_TZGGLX" style="width: 250px" placeholder="请选择任务状态"
              v-model="pageData.listQuery.state" selectType="select" :disabled="false" />
            <el-input placeholder="请输入标题或内容" v-model="pageData.listQuery.keywords" 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="isProvinces || isAuth">
          <el-icon>
            <Plus />
          </el-icon>新增
        </el-button>
        <el-button type="primary" v-loading="exportLoading" @click="export2Excel">导出</el-button>
      </section>
      <section :style="{ height: totalHeight }">
        <MOSTY.Table :table-columns="listTableConfig" :tableData="pageData.tableData" :tableloading="tableloading"
          :isSelect="true" :isSort="true" actionsW="280">
          <template #state="{ row }">
            <el-tag :type="getStateInfo(row.state)?.tagType">
              {{ getStateInfo(row.state)?.label }}
            </el-tag>
          </template>
          <template #type="{ row }">
            <el-tag :type="row.type == '01' ? 'success' : 'info'">{{ row.type == "01" ? "下发" : "接收" }}</el-tag>
          </template>
          <!-- v-if="isProvinces" -->
          <template #actions="{ row }">
            <el-popconfirm confirm-button-text="是" v-if="row.state == '01'" cancel-button-text="否" icon-color="red"
              title="确定要发布?" @confirm="handleClick(row, 'fb')">
              <template #reference>
                <span class="operedit">
                  <el-icon>
                    <Promotion />
                  </el-icon>发布
                </span>
              </template>
            </el-popconfirm>

            <span class="operesee" @click="handleMaskData('view', '详情', row.id, row.type)">
              <el-icon>
                <View />
              </el-icon>详情
            </span>

            <span class="operesee" v-if="row.state == '03'" @click="handleClick(row, 'qs')">
              <el-icon>
                <View />
              </el-icon>签收
            </span>
            <span class="operedit" v-if="row.state == '01'" @click="handleMaskData('edit', '修改', row.id)">
              <el-icon>
                <EditPen />
              </el-icon>修改
            </span>
            <span class="operedit" v-if="row.state == '04'" @click="handleMaskData('feedback', '反馈', row.id)">
              <el-icon>
                <EditPen />
              </el-icon>去反馈
            </span>
            <span class="operedit" v-if="row.state == '06'" @click="handleMaskData('feedback', '反馈', row.id)">
              <el-icon>
                <EditPen />
              </el-icon>重新反馈
            </span>
            <span class="operedit" v-if="row.state == '04'" @click="handleMaskData('issue', '分发', row.id)">
              <el-icon>
                <EditPen />
              </el-icon>去分发
            </span>
            <el-popconfirm confirm-button-text="是" v-if="row.state == '02'" cancel-button-text="否" icon-color="red"
              title="确定要撤回?" @confirm="handleClick(row, 'ch')">
              <template #reference>
                <span class="operedit">
                  <el-icon>
                    <EditPen />
                  </el-icon>撤回
                </span>
              </template>
            </el-popconfirm>

            <!-- <el-popconfirm confirm-button-text="是" v-if="row.state == '04'" cancel-button-text="否" icon-color="red" title="确定要下发?" @confirm="handleClick(row, 'xf')">
              <template #reference>
                <span class="operedit">
                  <el-icon> <EditPen /> </el-icon>去分发
                </span>
              </template>
            </el-popconfirm> -->

            <el-popconfirm v-if="row.state == '01'" confirm-button-text="是" cancel-button-text="否" icon-color="red"
              title="确定要删除?" @confirm="handleClick(row, 'sc')">
              <template #reference>
                <span class="operdel" size="small">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </span>
              </template>
            </el-popconfirm>
          </template>
          <!-- <template #actions="{ row }" v-else>
            <span class="operesee" @click="handleMaskData('view', '详情', row.id, row.type)">
              <el-icon> <View /> </el-icon>详情
            </span>
            <el-popconfirm
              v-if="isDwData(row.orgId) && row.state == '02'"
              confirm-button-text="是"
              cancel-button-text="否"
              icon-color="red"
              title="确定要撤回?"
              @confirm="handleClick(row, 'ch')"
            >
              <template #reference>
                <span class="operedit">
                  <el-icon> <EditPen /> </el-icon>撤回
                </span>
              </template>
            </el-popconfirm>
            <el-popconfirm v-if="isDwData(row.orgId)" confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?" @confirm="handleClick(row, 'sc')">
              <template #reference>
                <span class="operdel" size="small">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除</span
                >
              </template>
            </el-popconfirm>
          </template> -->
        </MOSTY.Table>
      </section>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
          @changeSize="handleSizeChange" />
      </div>
    </div>
  </div>
  <!-- 新增 / 编辑 / 分发 -->
  <div v-if="addAndEditShow" class="dialog-box">
    <AddAndEdit :title="title" :type="type" @close="() => handleClose('add')" :id="detailId" />
  </div>
  <!-- 反馈 -->
  <div v-if="actionVisible" class="dialog-box">
    <FeedbackAction :title="title" :type="type" @close="() => handleClose('feedback')" :id="detailId" />
  </div>

  <div v-if="detailVisible" class="dialog-box">
    <Detail :title="title" :type="type" @close="() => handleClose('view')" :id="detailId" />
  </div>
</template>
<script setup>
import * as MOSTY from "@/components/MyComponents/index"
import AddAndEdit from "./AddAndEdit.vue"
import FeedbackAction from "./FeedbackAction.vue"
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, ElLoading } from "element-plus"
import { getItem } from "@/utils/storage"
import Total from "./Total.vue"
import { listTableConfig } from "../models/list"
import { exportXlsx } from "@/excel/Export2Excel.js"
// import { Parser} from 'htmlparser2'

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

const D_BZ_TZGGLX = [
  { label: "未发布", value: "01", tagType: "info" },
  { label: "已发布", value: "02", tagType: "" },
  { label: "待签收", value: "03", tagType: "info" },
  { label: "待反馈", value: "04", tagType: "info" },
  { label: "反馈审批中", value: "05", tagType: "" },
  { label: "反馈审批拒绝", value: "06", tagType: "danger" },
  { label: "审批通过", value: "07", tagType: "success" }
]

// 创建返回查找函数的计算属性
const getStateInfo = computed(() => {
  return state => D_BZ_TZGGLX.find(t => t.value === state)
})

const props = defineProps({
  isShowTotal: {
    type: Boolean,
    default: false
  }
})
const tableloading = ref(false)
// 新增 / 编辑
const addAndEditShow = ref(false)
const actionVisible = ref(false)
// 导出
const exportLoading = ref(false)
// 详情Visible
const detailVisible = 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: "",
    state: "",
    time: []
  },
  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1,
    total: 0
  },
  tableColumns: [
    {
      title: "类型",
      prop: "type",
      slot: true
    },
    {
      title: "下发单位",
      prop: "orgName"
    },
    {
      title: "通知公告标题",
      prop: "title"
    },
    // {
    //     title: "通知公告内容",
    //     prop: "content",
    //     slot: true
    // },
    {
      title: "下发时间",
      prop: "issuedTime"
    },

    {
      title: "下发部门",
      prop: "deptName"
    },
    {
      title: "撰稿人",
      prop: "writer"
    },
    {
      title: "状态",
      prop: "state",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  tableData: []
})
const fromObj = ref()
const totalHeight = ref(null)
// 是否是安全部门
const isAqbm = computed(() => {
  return filterqx("isaqbm") == "1"
})
// 是否是省账号
const isProvinces = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isSgs") == "1"
})
// 是否是市账号
const isAuth = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") == "1" ? true : false
})
// 是否是本单位数据
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 - ${340 + getHeight.value.offsetHeight + queryHeight.value.offsetHeight}px)`
  })
})
// 关闭弹窗
const handleClose = val => {
  if (val === "view") {
    detailVisible.value = false
  } else if (val === "feedback") {
    actionVisible.value = false
  } else {
    addAndEditShow.value = false
  }
  queryData()
}
// 重置过滤条件
const handleRest = () => {
  Object.assign(pageData.listQuery, {
    keywords: "",
    state: "",
    time: []
  })
  pageData.pageConfiger.pageCurrent = 1
  queryData()
}
//列表查询
const queryData = () => {
  tableloading.value = true
  const params = {
    ...pageData.listQuery,
    startTime: pageData.listQuery.time?.length ? pageData.listQuery.time[0] : null,
    endTime: pageData.listQuery.time?.length ? pageData.listQuery.time[1] : null
  }
  postApi({ ...pageData.pageConfiger, ...params }, "/mosty-jcgl/taskController/queryTaskInfo")
    // postApi({ ...pageData.pageConfiger, ...params }, "/mosty-jcgl/noticeController/queryNoticeInfo")
    .then(res => {
      if (res) {
        pageData.tableData = res.records
        pageData.pageConfiger.total = res.total
      }
    })
    .finally(() => {
      tableloading.value = false
    })
}
//新增 / 修改 / 去分发 / 去反馈 弹窗
/**
 * _type?: 01 02; 类型，接收 or 下发
 * val:标识
 */
const handleMaskData = (val, _title, _id, _type) => {  
  detailId.value = _id
  title.value = "督办任务" + _title

  if (["view"].includes(val)) {
    // 不可编辑
    type.value = _type || val
    detailVisible.value = true
  } else if (["feedback"].includes(val)) {
    // 反馈
    type.value = val
    actionVisible.value = true
  } else {
    // 新增 / 修改 / 分发
    type.value = val
    addAndEditShow.value = true
  }
}

// 发布 / 删除 / 撤回
const handleClick = (row, type) => {
  const _url = "/mosty-jcgl/taskController"
  const urlMap = {
    sc: `${_url}/delTaskInfo`, // 删除
    ch: `${_url}/withdrawTaskInfo`, // 撤回
    qs: `${_url}/acceptTask`, // 签收
    xf: `${_url}/issuedNoticeInfo`, //
    fb: `${_url}/issuedTaskById` // 发布
  }
  const messageMap = {
    sc: "删除成功",
    ch: "撤回成功",
    qs: "签收成功",
    xf: "下发成功",
    fb: "发布成功"
  }
  let _data = type == "sc" ? [row.id] : { id: row.id }
  let _r = type == "sc" ? postApi : getApi
  _r(_data, urlMap[type]).then(() => {
    ElMessage.success(messageMap[type])
    queryData()
  })
}
//页码发生变化
const handleCurrentChange = val => {
  pageData.pageConfiger.pageCurrent = val
  if (isAqbm.value) {
    queryData()
  }
}
//查询条数发生变化
const handleSizeChange = val => {
  pageData.pageConfiger.pageSize = val
  if (isAqbm.value) {
    queryData()
  }
}

// const handler = { 
//     onopentag: (name, attributes) => { 
//         console.log('开始标签:', name, attributes); 
//     }, 
//     ontext: (text) => { 
//         console.log('文本内容:', text); 
//     }, 
//     onclosetag: (name) => { 
//         console.log('结束标签:', name); 
//     } 
// }; 

// const parser = new Parser(handler, { decodeEntities: true }); 

//导出表格
const export2Excel = async () => {
  
  let title = {
    xh: "序号",
    typeDesc: "任务类型",
    title: "标题",
    content: "任务描述",
    orgName: "发布单位",
    userName: "发布人",
    issuedTime: "任务发布日期",
    feedBackDate: "反馈期限",
    stateDesc: "状态",
  }

  const params = {
    ...pageData.listQuery,
    startTime: pageData.listQuery.time?.length ? pageData.listQuery.time[0] : null,
    endTime: pageData.listQuery.time?.length ? pageData.listQuery.time[1] : null,
    pageCurrent: 1,
    pageSize: 10000
  }
  exportLoading.value = true
  try {
    let res = await postApi(params, "/mosty-jcgl/taskController/queryTaskInfo")
    exportLoading.value = false
    let tableList = Array.isArray(res?.records) ? res.records : []
    if (!tableList.length) {
      ElMessage.warning("暂无数据可导出！")
      return
    }
    tableList.forEach((el) => {
      el.typeDesc = el.type == "01" ? "下发" : "接收"
      el.stateDesc = getStateInfo.value(el.state)?.label
      // el.content = parser.write(el.content)
      // parser.end(); 
    })

    let tablename = "督办任务.xlsx"
    
    exportXlsx(title, tableList, "督办任务", tablename, "督办任务")
  } catch (error) {
    ElMessage.warning("导出失败，请稍后再试！")
    exportLoading.value = false
  }
}
</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>
