<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-group ">
        <div class="filter-lable" style="width: 60px">
          相关方单位名称：
        </div>
        <div class="filter-width">
          <el-input v-model="KEYWORDS" placeholder="相关方单位名称" class="filter-item" style="width: 150px;"/>
        </div>
      </div>
      <div class="filter-group ">
        <div class="filter-lable" style="width: 60px">开户时间：</div>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"/>
      </div>
      <div class="filter-group ">
        <div class="filter-lable" style="width: 60px">属地：</div>
        <el-cascader
          ref="POSSESSION_SEARCH"
          v-model="queryForm.POSSESSION"
          :options="areaList"
          :props="areaProps"
          placeholder="请选择属地"
          style="width: 50%"
          @change="cascaderChange"/>
      </div>

      <div class="filter-group ">
        <div class="filter-lable" style="width: 60px">
          主管部门：
        </div>
        <div class="filter-width" style="width: 10px">
          <SelectTree
            ref="treeSelect"
            :clearable="false"
            :options="treeData"
            :props="defaultProps"
            v-model="queryForm.MAIN_DEP"
            placeholder="请选择主管部门"
            style="width: 300px"
          />
        </div>
      </div>
    </div>
    <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
      搜索
    </el-button>
    <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="resetSearch">
      重置
    </el-button>
    <el-table
      v-loading="listLoading"
      ref="multipleTable"
      :data="varList"
      :row-key="getRowKey"
      :header-cell-style="{
        'font-weight': 'bold',
        'color': '#000'
      }"
      :row-class-name="tableRowClassName"
      tooltip-effect="dark"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        :reserve-selection="true"
        type="selection"
        width="55"
        align="center"/>
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="RELEVANT_UNIT_NAME" label="相关方单位名称" />
      <el-table-column label="属地">
        <template slot-scope="{row}">
          <span v-if="row.COMPANY_AREA">
            {{ row.COMPANY_AREA.replaceAll(',',' ') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="MAIN_DEPARTMENT_NAME" label="主管部门" />
      <el-table-column prop="CREATOR" label="开户人员" />
      <!--    :formatter="(row) => formatStateLabel(row)"   -->
      <el-table-column :formatter="(row) => formatStateLabel(row)" prop="STATE" label="状态" />
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="{row}">
          <el-button type="danger" icon="el-icon-refresh" size="mini" @click="resetPassword(row)">重置密码</el-button>
          <!--      @click="goEditPage(row.CORPINFO_ID)"     -->
        <!-- <el-button type="success" icon="el-icon-edit" size="mini">修改</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新建相关方单位</el-button>
      </div>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>

  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import SelectTree from '@/components/SelectTree'
export default {
  components: { Pagination, SelectTree },
  directives: { waves },
  data() {
    return {
      date: [],
      startDate: '',
      endDate: '',
      treeData: [],
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      DEPTIDS: '',
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      KEYWORDS: '',
      varList: [],
      pd: [],
      areaList: [], // 省市县列表
      areaProps: {
        lazy: true,
        lazyLoad: async(node, resolve) => {
          const resData = await this.getAreaDict(
            (node.data && node.data.DICTIONARIES_ID) || 'e725d2a91b8248f4b8f49889038df7de'
          )
          const { level } = node
          resolve(
            resData.map((item) => {
              return {
                DICTIONARIES_ID: item.DICTIONARIES_ID,
                BIANMA: item.BIANMA,
                NAME: item.NAME,
                leaf: level >= 3
              }
            })
          )
        },
        value: 'BIANMA',
        id: 'DICTIONARIES_ID',
        label: 'NAME',
        children: 'children',
        checkStrictly: true
      },
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      queryForm: {
        POSSESSION: '', // 属地
        MAIN_DEP: '', // 主管部门
        PROVINCE: '',
        CITY: '',
        COUNTY: '',
        VILLAGE: '',
        cteateDate: ''
      }
    }
  },
  created() {
    // this.ROLE_ID
    this.getList()
    this.getTreeList()
  },
  methods: {
    getTreeList() {
      requestFN(
        '/corpinfo/getRegulatoryDepList',
        {}
      ).then((data) => {
        this.treeData = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
      })
    },
    async getAreaDict(DICTIONARIES_ID) {
      const { list } = await requestFN(
        '/dictionarisearea/getLevels',
        {
          DICTIONARIES_ID
        }
      )
      return list
    },
    cascaderChange(e) {
      this.$nextTick(() => {
        const dom = document.getElementsByClassName('el-radio is-checked')
        const radioDom = dom[dom.length - 1]
        const brother = radioDom.nextElementSibling
        if (radioDom.getElementsByClassName('el-radio__original')[0].value.split(',').length < 4) {
          brother.click()
        }
      })
    },
    tableRowClassName({ row, rowIndex }) {
      var timeType = this.judgeTime(row.CREATTIME)
      if (timeType == 1) {
        return 'yellow-row'
      } else if (timeType == 2) {
        return 'red-row'
      }
      return ''
    },
    judgeTime(startTime) {
      startTime = startTime.replace(/\-/g, '/')
      var endTime = new Date()
      var sTime = new Date(startTime) // 开始时间
      var eTime = new Date(endTime) // 结束时间
      var timeType = 1000 * 3600 * 24
      var differDay = (eTime.getTime() - sTime.getTime()) / timeType
      var nineMon = 270
      var oneYear = 365
      if (differDay >= oneYear) {
        return 2
      }
      if (differDay >= nineMon) {
        return 1
      }
      return 0
    },
    getRowKey(row) {
      return row.CORPINFO_ID
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      if (this.date.length > 1) {
        this.startDate = this.date[0] + ' ' + '00:00:00'
        this.endDate = this.date[1] + ' ' + '23:59:59'
      } else if (this.date.length == 1) {
        this.startDate = this.date[0] + ' ' + '00:00:00'
      }
      requestFN(
        '/corpinfo/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          startDate: this.startDate,
          endDate: this.endDate,
          PROVINCE: this.queryForm.POSSESSION[0] || '',
          CITY: this.queryForm.POSSESSION[1] || '',
          COUNTY: this.queryForm.POSSESSION[2] || '',
          VILLAGE: this.queryForm.POSSESSION[3] || '',
          STREET: this.queryForm.POSSESSION[4] || '',
          MAIN_DEP: this.queryForm.MAIN_DEP
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
        this.hasButton()
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 判断按钮权限，用于是否显示按钮
    hasButton: function() {
      var keys = 'corpinfo:add,corpinfo:del,corpinfo:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.corpinfofhadminadd		// 新增权限
        this.del = data.corpinfofhadmindel		// 删除权限
        this.edit = data.corpinfofhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 编辑
    goEditPage(ID) {
      this.$parent.activeName = 'CorpInfoEdit'
      this.$parent.CORPINFO_ID = ID
    },
    // 新增
    handleAdd() {
      this.$parent.activeName = 'CorpInfoAdd'
    },
    // 重置
    resetSearch() {
      this.queryForm.POSSESSION = ''
      this.queryForm.MAIN_DEP = ''
      this.queryForm.PROVINCE = ''
      this.queryForm.CITY = ''
      this.queryForm.COUNTY = ''
      this.queryForm.VILLAGE = ''
      this.queryForm.cteateDate = ''
      this.date = []
      this.KEYWORDS = ''
      this.startDate = ''
      this.endDate = ''
      this.getList()
    },
    // 转换企业状态
    formatStateLabel(row) {
      const status = row.STATE
      if (status) {
        if (status === '0') {
          return '未填报'
        } else if (status === '-1') {
          return '未审核'
        } else if (status === '1') {
          return '待审核'
        } else if (status === '2') {
          return '审核通过'
        } else if (status === '3') {
          return '已打回'
        } else if (status === '4') {
          return '已填报'
        }
      }
      return status
    },
    // 重置密码
    resetPassword(row) {
      this.$confirm('确定重置该企业的密码?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/corpinfo/resetPasswordByCorpInfoId',
          {
            CORPINFO_ID: row.CORPINFO_ID,
            RELEVANT_UNIT_NAME: row.RELEVANT_UNIT_NAME
          }
        ).then(() => {
          this.$message({
            message: '重置成功',
            type: 'success'
          })
          this.listLoading = false
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    }
  }
}

</script>
<style>
.el-table .yellow-row {
  background: #f8e71c;
}

.el-table .red-row {
  background: #fc0221;
}
</style>
