<template>
  <div class="main-content m20">
    <div class="content-header">
      <div v-if="tabName == 'market'" class="body search-body">
        <!-- 查询条件行：三个条件平均分配宽度，确保同一行显示 -->
        <el-row style="margin-bottom:10px;">
          <!-- 统一社会信用代码/注册号 -->
          <el-col :span="8">
            <el-row type="flex" align="center">
              <label class="label-name">统一社会信用代码/注册号：</label>
              <el-input
                v-model.trim="searchAbnForm.searchUscc"
                size="mini"
                placeholder="精准查询"
                class="custom-input"
              />
            </el-row>
          </el-col>

          <!-- 主体名称 -->
          <el-col :span="8">
            <el-row type="flex" align="center">
              <label class="label-name">筛选类型：</label>
              <el-select v-model="searchAbnForm.entType" clearable size="mini" placeholder="请选择主体类型" class="custom">
                <el-option
                  v-for="item in entTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-row>
          </el-col>

          <!-- 办理机关 -->
          <el-col :span="8" v-if="isCityBureau">
            <el-row type="flex" align="center">
              <label class="label-name">办理机关：</label>
              <el-select
                v-model="searchAbnForm.orgNumber"
                clearable
                size="mini"
                placeholder="请选择办理机关"
                class="custom-input"
              >
                <el-option
                  v-for="item in orgList"
                  :key="item.orgNumber"
                  :label="item.orgUnitName"
                  :value="item.orgNumber"
                />
              </el-select>
            </el-row>
          </el-col>
        </el-row>

        <!-- 按钮行 -->
        <el-row style="margin-bottom:10px">
          <el-col :span="24" style="text-align: right; padding-right: 20px;">
            <div class="btn-box">
              <el-button size="mini" type="primary" @click="searchAbnList" :loading="abnLoading">查询</el-button>
              <el-button size="mini" @click="searchAbnForm.searchIntoDate = '';searchAbnForm.entName='';searchAbnForm.searchUscc='';searchAbnForm.intoDecorg='';searchAbnForm.specause='';searchAbnForm.redecorg='';searchAbnForm.orgNumber='';searchAbnForm.operatestatus='';searchAbnForm.entType=''">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 表格内容区域 -->
    <div v-if="tabName == 'market'" class="content-body">
      <div style="margin-bottom: 10px; margin-right: 50px; text-align: right;">
        <el-button type="primary" size="mini" @click="exportqzzxList()" :loading="abnLoading">导出Excel</el-button>
      </div>

      <el-table
        ref="multipleTable"
        v-loading="abnLoading"
        :data="abnTableData"
        tooltip-effect="dark"
        style="width: 95%; margin: 0 auto;"
        :fit="true"
        :row-class-name="tableRowClassName"
        :header-cell-style="{ background: '#8cc3fb', color: '#fff' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column prop="index" label="序号" min-width="30" align="center" />
        <el-table-column prop="busName" :show-overflow-tooltip="true" label="企业名称" min-width="90" align="left" />
        <el-table-column prop="uniscid" :show-overflow-tooltip="true" label="社会统一信用代码" min-width="120" align="left" />
        <el-table-column prop="regno" label="注册号" min-width="40" align="left"/>
        <el-table-column prop="regulatoryNameTemp" :show-overflow-tooltip="true" label="属地市场所" min-width="60" align="left" />
        <el-table-column prop="regorg_CN" label="所属区局" min-width="40" align="left" />
        <el-table-column prop="regstate_CN" label="企业状态" min-width="40" align="left" />
      </el-table>

      <!-- 分页 -->
      <div class="page-box">
        <el-pagination
          :disabled="abnLoading"
          :page-size="pageAbnParam.pageSize"
          :total="pageAbnParam.total"
          :current-page="pageAbnParam.curPage"
          :page-sizes="[10, 20, 30, 40, 50, 100, 200]"
          layout="slot,total, sizes, prev, pager, next, jumper"
          @size-change="pageSizeChangeAbn"
          @current-change="pageIndexChangeAbn"
        >
          <span>
            第 {{ pageAbnParam.curPage }} 页 /
            共 {{ (pageAbnParam.total !== 0 ? parseInt((pageAbnParam.total + pageAbnParam.pageSize - 1) / pageAbnParam.pageSize) : 1) }} 页
          </span>
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  businessQuery,
  queryAllOrg,
  queryxyxfCqList,
  queryqzzxEntList,
  exportqzzxList
} from '@/api/comprehensive'
import { isPassDissentApply } from '@/api/abnormal'
import { getConstant, getSliceTreeList } from '@/api/system'
import { getBaseCodeList } from '@/api/constant'

export default {
  data() {
    return {
      isCityBureau: false, // 新增：标记是否为市局用户
      ressonList: [],
      sliceOptions: [],
      tabName: 'market',
      tabBusType: '',
      tabPosition: 'current',
      currentData: [],
      historyData: [],
      historyloading: false,
      orgList: [],
      orgMarketList: [
        {
          value: '市局',
          label: '广州市市场监督管理局'
        },{
          value: '荔湾',
          label: '广州市荔湾区市场监督管理局'
        },{
          value: '越秀',
          label: '广州市越秀区市场监督管理局'
        },{
          value: '海珠',
          label: '广州市海珠区市场监督管理局'
        },{
          value: '白云',
          label: '广州市白云区市场监督管理局'
        },{
          value: '黄埔',
          label: '广州市黄埔区市场监督管理局'
        },{
          value: '花都',
          label: '广州市花都区市场监督管理局'
        },{
          value: '从化',
          label: '广州市从化区市场监督管理局'
        },{
          value: '增城',
          label: '广州市增城区市场监督管理局'
        },{
          value: '番禺',
          label: '广州市番禺区市场监督管理局'
        },{
          value: '南沙',
          label: '广州市南沙区市场监督管理局'
        },{
          value: '天河',
          label: '广州市天河区市场监督管理局'
        },{
          value: '注册二处',
          label: '广州市市场监督管理局登记注册二处'
        }
      ],
      showMore: false,
      searchNameP: '',
      busyTypes: [],
      searchForm: {
        uniscid: '',
        acceptno: '',
        searchName: '',
        busType: '',
        busStatus: '',
        searchDate: '',
        bustypeAndCurrentNode: [],
        orgNumber: ''
      },
      searchAbnForm: {
        searchUscc: '',
        entName: '',
        searchIntoDate: '',
        searchRemDate: '',
        intoDecorg: '',
        redecorg: '',
        specause: '',
        entType:'',
        operatestatus:''
      },
      loading: false,
      abnLoading: false,
      tableData: [],
      abnTableData: [],
      busstatusOptions: [{
        value: '1',
        label: '待受理'
      }, {
        value: '2',
        label: '待审核'
      }, {
        value: '3',
        label: '待审批'
      }, {
        value: '4',
        label: '审批通过'
      }, {
        value: '5',
        label: '审批不通过'
      }, {
        value: '6',
        label: '材料补正'
      }, {
        value: '7',
        label: '作废办结'
      }],
      bustypeOptions: [],
      user: JSON.parse(sessionStorage.getItem('user')),
      pageParam: {
        customParamMap: {},
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      pageAbnParam: {
        customParamMap: {},
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      pageParamhistory: {
        customParamMap: {},
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      entTypeOptions: [
        { value: '0', label: '吊销未注销、撤销' },
        { value: '1', label: '排除法律、行政法规或者国务院决定规定公司在注销登记前须经批准的' }
      ],
      operatestatusOptions: [
        {value: '0', label: '移出'},
        {value: '1', label: '列入'},
      ],
      exportQueryData: {}, // 导出excel的查询条件, 用于导出excel, 每轮查询成功后赋值
      REGSTATEList: [],
    }
  },
  mounted() {
    this.judgeIsCityBureau() // 新增：初始化时判断身份
    // 加载办理机关
    this.getOrgList()
    this.getCache()
  },
  methods: {
    // 新增：判断是否为市局用户
    judgeIsCityBureau() {
      const user = JSON.parse(sessionStorage.getItem('user'))
      // 假设市局orgCode为440100，可根据实际调整判断条件（如orgName）
      this.isCityBureau = user && user.orgCode === '440101'
    },
    exportqzzxList(){
      if (this.pageAbnParam.total === 0) {
        this.$message({
          message: '未查询到数据，无法导出！',
          type: 'warning'
        })
        return
      }
      const data = JSON.parse(JSON.stringify(this.exportQueryData))
      // const pageParam = this.pageAbnParam
      // pageParam.paramMap = {
      //   ...this.searchAbnForm
      // }
      this.abnLoading = true
      exportqzzxList(data).then(res => {
        const url = window.URL.createObjectURL(res, { type: 'application/vnd.ms-excel;charset=utf-8' })
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', '强制注销名单.xlsx')
        link.click()
      }).finally(() => this.abnLoading = false)
    },
    getOrgList() {
      queryAllOrg().then(res => {
        if (res.code === 0) {
          let orgCode = JSON.parse(sessionStorage.getItem('user')).orgCode
          res.data.forEach(each => {
            if(orgCode == "440101" ){
              this.orgList.push(each)
            }else if(orgCode == each.orgNumber){
              this.orgList.push(each)
            }
          })
        }
      })
    },
    showMoreCriteria() {
      this.showMore = !this.showMore
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    // 公示提示
    tip() {
      return this.$message.error('该主体公示中')
    },
    // 搜索
    search() {
      this.pageParam.customParamMap = this.searchForm
      this.pageParam.curPage = 1
      this.loadPage()
    },
    searchAbnList(){
      this.pageAbnParam.customParamMap = this.searchAbnForm
      // 判断是否填写了条件
      let flag = false
      // obj的遍历
      Object.keys(this.pageAbnParam.customParamMap).forEach(key => {
        if (key === 'regulatory') {
          if (this.pageAbnParam.customParamMap[key].length > 0) {
            flag = true
          }
        } else {
          if (this.pageAbnParam.customParamMap[key] !== '' && this.pageAbnParam.customParamMap[key] !== null) {
            flag = true
          }
        }
      })
      if (!flag) {
        this.$message({
          message: '请至少填写一个查询条件！',
          type: 'warning'
        })
        return
      }
      this.exportQueryData = null
      this.pageAbnParam.curPage = 1
      this.loadAbnPage()
    },
    // 分页多选插件回调
    removeCallback(index, row) {
      this.$refs.multipleTable.toggleRowSelection(row, false)
    },
    // 全选按钮事件
    selectAll() {
      const table = this.$refs.multipleTable
      for (const i in table.data) {
        const each = table.data[i]
        table.toggleRowSelection(each, true)
      }
    },
    // 选项变更事件
    handleSelectionChange(selectData) {
      const cancel = []
      if (selectData.length !== this.tableData.length) {
        // 找出没有选中的内容
        this.tableData.forEach(each => {
          for (const i in selectData) {
            const atom = selectData[i]
            if (atom.pripid === each.pripid) {
              return
            }
          }
          cancel.push(each)
        })
      }
      // 取消选中的内容
      for (const i in cancel) {
        const each = cancel[i]
        let index
        for (const j in this.selection) {
          const select = this.selection[j]
          if (select.pripid === each.pripid) {
            index = parseInt(j)
            break
          }
        }
        if (index !== undefined) {
          this.selection.splice(index, 1)
        }
      }
      // 增加选中内容
      for (const i in selectData) {
        const each = selectData[i]
        let exist = false
        for (const j in this.selection) {
          const select = this.selection[j]
          if (select.pripid === each.pripid) {
            exist = true
            break
          }
        }
        if (!exist) {
          this.selection.push(each)
        }
      }
    },
    // 当前分页改变
    pageIndexChange(curPage) {
      this.pageParam.curPage = curPage
      this.loadPage()
    },
    pageIndexChangeAbn(curPage) {
      this.pageAbnParam.curPage = curPage
      this.loadAbnPage()
    },
    // 分页大小改变
    pageSizeChange(pageSize) {
      this.pageParam.pageSize = pageSize
      this.loadPage()
    },
    pageSizeChangeAbn(pageSize) {
      this.pageAbnParam.pageSize = pageSize
      this.loadAbnPage()
    },
    // 当前分页改变
    historyPageIndexChange(curPage) {
      this.pageParamhistory.curPage = curPage
      this.loadPage()
    },
    // 分页大小改变
    historyPageSizeChange(pageSize) {
      this.pageParamhistory.pageSize = pageSize
      this.loadPage()
    },
    // 加载分页
    loadAbnPage() {
      if (this.abnLoading) return
      let data = {}
      if(this.exportQueryData){
        this.exportQueryData.curPage = this.pageAbnParam.curPage
        this.exportQueryData.pageSize = this.pageAbnParam.pageSize
        data = JSON.parse(JSON.stringify(this.exportQueryData))
      }else{
        data = this.pageAbnParam
      }
      this.abnLoading = true
      queryqzzxEntList(data).then(res => {
        this.exportQueryData = JSON.parse(JSON.stringify(data))
        this.abnLoading = false
        const list = []
        let i = 1
        const pageStart = (this.pageAbnParam.curPage - 1) * this.pageAbnParam.pageSize
        res.data.records.forEach(each => {
          each.index = pageStart + i++
          list.push(each)
        })

        this.abnTableData = list
        this.pageAbnParam.total = res.data.total
        sessionStorage.setItem('pageAbnParam-abnormal', JSON.stringify(this.pageAbnParam))
        sessionStorage.setItem('abnTableData-abnormal', JSON.stringify(this.abnTableData))
      })
    },
    loadPage() {
      if (this.loading) return
      this.loading = true
      this.historyloading = true
      this.pageParam.customParamMap.userId = this.user.primaryKey
      businessQuery(this.pageParam).then(res => {
        this.loading = false
        const list = []
        let i = 1
        const pageStart = (this.pageParam.curPage - 1) * this.pageParam.pageSize
        res.data.records.forEach(each => {
          each.index = pageStart + i++
          each.busTypeName = this.$util.getTaskBusinessTypeName(each.bustype)
          each.busStatusName = this.$util.getTaskNodeName(each.currentNodeOrBizStatus)
          each.isPassDissentApply = false
          if (each.bustype === '6') {
            isPassDissentApply(each.bustype, each.bizseqid).then(res => {
              each.isPassDissentApply = res.data.isPass
              each.acceptstat = res.data.acceptstat
              // 若通过受理审批环节且不同意 当前业务状态：不予受理
              if (each.isPassDissentApply === true && each.acceptstat === '0') {
                each.busStatusName = '不予受理'
              }
            })
          }
          list.push(each)
        })
        this.tableData = list
        this.pageParam.total = res.data.total
        if(this.tabBusType == 'abnormal'){
          sessionStorage.setItem('pageParam-abnormal', JSON.stringify(this.pageParam))
          sessionStorage.setItem('tableData-abnormal', JSON.stringify(this.tableData))
        }else if(this.tabBusType == 'illegal'){
          sessionStorage.setItem('pageParam-illegal', JSON.stringify(this.pageParam))
          sessionStorage.setItem('tableData-illegal', JSON.stringify(this.tableData))
        }else if(this.tabBusType == 'credit'){
          sessionStorage.setItem('pageParam-credit', JSON.stringify(this.pageParam))
          sessionStorage.setItem('tableData-credit', JSON.stringify(this.tableData))
        }else if(this.tabBusType == 'revoke'){
          sessionStorage.setItem('pageParam-revoke', JSON.stringify(this.pageParam))
          sessionStorage.setItem('tableData-revoke', JSON.stringify(this.tableData))
        }else if(this.tabBusType == 'cancel'){
          sessionStorage.setItem('pageParam-cancel', JSON.stringify(this.pageParam))
          sessionStorage.setItem('tableData-cancel', JSON.stringify(this.tableData))
        }else if(this.tabBusType == 'punish'){
          sessionStorage.setItem('pageParam-punish', JSON.stringify(this.pageParam))
          sessionStorage.setItem('tableData-punish', JSON.stringify(this.tableData))
        }else if(this.tabBusType == 'correct'){
          sessionStorage.setItem('pageParam-correct', JSON.stringify(this.pageParam))
          sessionStorage.setItem('tableData-correct', JSON.stringify(this.tableData))
        }
        // sessionStorage.setItem('pageParam-zhcx', JSON.stringify(this.pageParam))
        // sessionStorage.setItem('tableData-zhcx', JSON.stringify(this.tableData))
        if (this.searchForm.searchName !== '') {
          this.searchNameP = this.searchForm.searchName
        } else {
          this.searchNameP = ''
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.main-content {
  background: #fff;
  padding: 10pt;

  .content-header {
    background: white;

    .label-name {
      text-align: right;
      display: inline-block;
      width: 140px;
      margin-right: 8px;
      font-size: $table-content-font-size;
    }

    .custom-input {
      width: calc(100% - 148px); // 总宽度 - 标签宽度 - 间距
    }

    .search-input {
      cursor: pointer;
    }

    .body {
      padding: 20px 0;
      border-top: none;
      margin-bottom: 40px;
    }

    .btn-box {
      display: inline-block;
      padding-left: 10px;
    }
  }

  .content-body {
    background: white;
  }

  .header {
    .title {
      font-weight: 600;
      font-size: 1.2rem;
    }
  }

  .page-box {
    margin: 10px;
    text-align: right;
  }

  .mb10 {
    margin-bottom: 10px;
  }
}

// 统一输入框和选择框高度
/deep/ .el-input__inner,
/deep/ .el-select__inner {
  height: 28px;
}

// 优化flex布局的行
/deep/ .el-row[type="flex"] {
  width: 100%;
}

// 表格奇数行样式
/deep/ .warning-row {
  background-color: #f5f7fa;
}
</style>
