<template>
  <div class="icons-container">
    <el-container>
      <el-main>
        <el-form label-width="180px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="用户名" prop="USERNAME">
                <el-input v-model="searchForm.USERNAME" placeholder="用户名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="姓名" prop="NAME">
                <el-input v-model="searchForm.NAME" placeholder="姓名"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="证件状态" prop="CARD_STATUS">
                <el-select v-model="searchForm.CARD_STATUS" placeholder="请选择" style="width: 100%">
                  <el-option label="未过期" value="0" />
                  <el-option label="即将过期" value="2" />
                  <el-option label="已过期" value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <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="success" icon="el-icon-refresh" @click="goKeyReset">
                  重置
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table
          v-loading="listLoading"
          ref="multipleTable"
          :data="varList"
          :row-key="getRowKey"
          :header-cell-style="{
            'font-weight': 'bold',
            'color': '#000'
          }"
          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="USERNAME" label="用户名" />
          <el-table-column prop="NAME" label="姓名" />
          <el-table-column prop="BELONG_TO_CORP_NAME" label="相关方名称" />
          <el-table-column prop="DEPARTMENT_NAME" label="部门"/>
          <el-table-column prop="CLASS_NO" label="人员编号"/>
          <el-table-column prop="VALIDITY_PERIOD_END" label="证件到期日"/>

          <el-table-column prop="VALIDITY_PERIOD_END" label="证件状态">
            <template v-slot="{row}">
              <span v-if="getCardStatus(row.VALIDITY_PERIOD_END) == 0" :style="{color: 'green'}">未过期</span>
              <span v-if="getCardStatus(row.VALIDITY_PERIOD_END) == 2" :style="{color: 'orange'}">即将过期</span>
              <span v-if="getCardStatus(row.VALIDITY_PERIOD_END) == 1" :style="{color: 'red'}">已过期</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="left" width="200">
            <template slot-scope="{row}">
              <el-button v-if="row.ACCOUNT_TYPE != 0" type="success" icon="el-icon-view" size="mini" @click="toUserDetail(row)">查看</el-button>
              <el-button v-if="getCardStatus(row.VALIDITY_PERIOD_END) != 0" type="primary" size="mini" @click="sendMessage([row])">重新推送</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>
      </el-main>
    </el-container>
    <div class="heightt"/>
<!--    <div class="subdy-foot">-->
<!--      <el-row style="text-align: center">-->
<!--        <el-button @click="goBack">返回</el-button>-->
<!--      </el-row>-->
<!--    </div>-->
    <UserBaseInfoView ref="userbaseinfoview" :base_info_url="baseInfourl"/>
    <send-util ref="sendUtil" append-to-body @refresh="getList"/>
  </div>
</template>

<script>
import SelectTree from '@/components/SelectTree'
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import UserBaseInfoView from '@/components/UserBaseInfo/UserBaseInfoView'
import SendUtil from "../../synInfo/components/sendUtil.vue";

export default {
  components: {SendUtil, Pagination, SelectTree, UserBaseInfoView },
  directives: { waves },
  data() {
    return {
      userId: this.$parent.USER_ID_T,
      baseInfourl: '/user/getDetailByUserIdAndCorpInfoId',
      treeLoading: false,
      listLoading: false,
      add: true,
      del: true,
      edit: true,
      readonly: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      searchForm: {
        CARD_STATUS:'',
        DEPARTMENT_ID: '',
        USERNAME: '',
        NAME: '',
        DEPTNAME: '',
        AUDIT_STATE: '',
        ISFLOW: '',
        DEPART_STATE: '',
        AGE: '',
        IS_SIGN_LABOR: '',
        IS_INJURIES_PAY: '',
        ISPAY: '',
        IS_LEVEL_THREE: '',
        IS_SAFETY_TELL: '',
        IS_SPECIAL_JOB: ''
      },
      userForm: {
        PARENT_ID: '',
        USER_ID: '',
        DEPARTMENT_ID: '',
        DEPTNAME: '',
        USERNAME: '',
        NAME: ''
      },
      DEPARTMENT_ID: '',
      total: 0,
      PARENT_ID: '0',				// 上级ID
      varList: [],
      qyztList: [],
      options: [{
        value: '0',
        label: '启用'
      }, {
        value: '1',
        label: '禁用'
      }],
      STATE: [],
      industryList: [],
      countryList: [],
      villageList: [],
      treeData: [],
      CITY_CODE: '',
      COUNTRY: '',
      VILLAGE: '',
      config: config,
      dialogFormEdit: false,
      rules: {
        DEPTNAME: [{ required: true, message: '分公司名称不能为空', trigger: 'blur' }],
        USERNAME: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        NAME: [{ required: true, message: '姓名不能为空', trigger: 'blur' }]
      },
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      workTypeList: [] // 工种
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getCardStatus(VALIDITY_PERIOD_END) {
      const now = new Date(); // 当前时间
      const threeMonthsLater = new Date(now); // 三个月后的时间
      threeMonthsLater.setMonth(threeMonthsLater.getMonth() + 3); // 设置为未来三个月后的时间
      // 将VALIDITY_PERIOD_END转换为Date对象（假设它是一个有效的日期字符串）
      const validityPeriodEnd = new Date(VALIDITY_PERIOD_END);

      // 比较日期并返回状态
      if (now > validityPeriodEnd) {
        // 证件已过期
        return 1;
      } else if (validityPeriodEnd > now && validityPeriodEnd <= threeMonthsLater) {
        // 证件即将到期
        return 2;
      } else {
        return 0;
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleNodeClick(node, data, value) {
      this.searchForm.DEPARTMENT_ID = node.id
      this.getList(node.id)
    },
    // 获取数据字典数据
    getDict() {
      requestFN(
        'dictionaries/getLevels',
        { DICTIONARIES_ID: '55484e491a5e442d839c4595380713ec' }
      ).then((data) => {
        this.workTypeList = data.list
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/user/cardOverdueList?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          CORPINFO_ID: JSON.parse(sessionStorage.getItem('user')).CORPINFO_ID,
          NAME: this.searchForm.NAME,
          USERNAME: this.searchForm.USERNAME,
          CARD_STATUS: this.searchForm.CARD_STATUS,
          SEND_TYPE: 1
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
      }).catch((e) => {
        this.listLoading = false
      })
    },
    sendMessage(row) {
      this.$refs.sendUtil.init(row,1)
    },
    getRowKey(row) {
      return row.USER_ID
    },
    goReturn() {
      this.$parent.activeName = 'CorpInfoList'
    },
    // 搜索
    getQuery() {
      this.getList()
    },
    getTreeList() {
      this.treeLoading = true
      requestFN(
        '/xgf/department/listzTree',
        {
          CORPINFO_ID: this.$parent.CORPINFO_ID
        }
      ).then((data) => {
        this.treeLoading = false
        this.treeData = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
        this.treeLoading = false
      })
    },
    getCountryList() {
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: this.CITY_CODE
        }
      ).then((data) => {
        this.countryList = data.list
      }).catch((e) => {
      })
    },
    getVillageList(value, id) {
      this.COUNTRY = value
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: id
        }
      ).then((data) => {
        this.villageList = data.list
      }).catch((e) => {
      })
    },
    changeVillage(village) {
      this.VILLAGE = village
    },
    // 查看
    toUserDetail(ROW) {
      this.$refs.userbaseinfoview.openWindow(ROW.USER_ID, JSON.parse(sessionStorage.getItem('user')).CORPINFO_ID ,ROW.EMPLOYMENT_APPLY_MANAGEMENT_ID)
    },
    userEdit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          requestFN(
            '/user/editCorpUser',
            {
              ...this.userForm
            }
          ).then((data) => {
            this.$message.success('修改成功')
            this.dialogFormEdit = false
            this.getList()
          }).catch((e) => { this.listLoading = false })
        } else {
          return false
        }
      })
    },
    handleDelete(id, name) {
      this.$confirm('确定要删除[' + name + ']吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/user/deleteCorpUser',
          {
            USER_ID: id
          }
        ).then((data) => {
          if (data.result == 'success') {
            this.listLoading = false
            this.getList()
          }
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    goBack() {
      this.$parent.activeName = 'CardOverdueList'
    },
    enableORDisable(ISUSE, CORPINFO_ID) {
      this.$confirm(ISUSE === '0' ? '确定要启用该账户吗?' : '确定要禁用该账户吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/corpinfo/editisuse',
          {
            CORPINFO_ID,
            ISUSE
          }
        ).then(() => {
          this.$message({
            message: ISUSE === '0' ? '启用成功' : '禁用成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {})
    },
    handleAdd() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length === 0) {
        this.$message({
          message: '未勾选人员...',
          type: 'error'
        })
        return false
      }
      this.$refs.sendUtil.init(_selectData,1)
    },
    // 判断按钮权限，用于是否显示按钮
    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
      })
    },
    goKeyReset() {
      this.searchForm = {
        DEPARTMENT_ID: '',
        USERNAME: '',
        NAME: '',
        DEPTNAME: '',
        AUDIT_STATE: '',
        ISFLOW: '',
        DEPART_STATE: '',
        AGE: '',
        IS_SIGN_LABOR: '',
        IS_INJURIES_PAY: '',
        ISPAY: '',
        IS_LEVEL_THREE: '',
        IS_SAFETY_TELL: '',
        IS_SPECIAL_JOB: ''
      }
      this.getList()
    },
    resetPwd(id) {
      this.$confirm('确定要重置选中的密码吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/corpinfo/resetPwd',
          {
            CORPINFO_ID: id
          }
        ).then(() => {
          this.$message({
            message: '重置成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    // 获取数据字典
    getDicList(list, DICTIONARIES_ID) {
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID
        }
      ).then((data) => {
        this[list] = data.list
      }).catch((e) => {
      })
    },
    translate(list, id) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].BIANMA === id || list[i].DICTIONARIES_ID === id) {
          return list[i].NAME
        }
      }
    },
    showBranchName(CORPINFO_ID, CORP_NAME) {
      this.$refs.form && this.$refs.form.resetFields()
      this.dialogFormEdit = true
      this.updateBranchNameForm.CORPINFO_ID = CORPINFO_ID
      this.updateBranchNameForm.CORP_NAME = CORP_NAME
    },
    updateBranchName(ID) {
      requestFN(
        '/department/listTreeCorpInfo',
        {
          CORPINFO_ID: ID
        }
      ).then((data) => {
        this.treeData = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
      })
    },
    // 转换企业状态
    formatLabel(row, type) {
      if (type === '0') {
        const special = row.IS_SPECIAL_JOB
        if (special === '1') {
          return '特殊工种'
        } else if (special === '0') {
          return '非特殊工种'
        } else {
          return special
        }
      } else if (type === '1') {
        const flow = row.ISFLOW
        if (flow === '1') {
          return '流动人员'
        } else if (flow === '0') {
          return '非流动人员'
        } else {
          return flow
        }
      } else if (type === '2') {
        const depart = row.DEPART_STATE
        if (depart === '1') {
          return '离职'
        } else if (depart === '0') {
          return '在职'
        } else {
          return depart
        }
      } else if (type === '3') {
        const audit = row.AUDIT_STATE
        if (audit === '0') {
          return '已打回'
        } else if (audit === '1') {
          return '待审核'
        } else if (audit === '2') {
          return '审核通过'
        } else {
          return audit
        }
      } else if (type === '5') {
        const train_status = row.STATUS
        if (train_status == 0) {
          return '未培训'
        } else if (train_status === 1) {
          return '培训中'
        } else if (train_status === 2) {
          return '培训通过'
        } else if (train_status === -1) {
          return '培训未通过'
        } else {
          return '未培训'
        }
      } else {
        return ''
      }
    }
  }
}
</script>
