<template>
  <div class="app-container">
    <el-form label-width="130px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="用户名">
            <el-input v-model="KEYWORDS" placeholder="请输入用户名"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="培训状态">
            <el-select v-model="STATUS" placeholder="请选择培训状态" style="width: 100%;" clearable>
              <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="10px">
            <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
      ref="multipleTable"
      :data="varList"
      :header-cell-style="{'font-weight': 'bold','color': '#000'}"
      tooltip-effect="dark"
      border
      fit
      highlight-current-row>
      <el-table-column :selectable="handleSelectWithDifferentStatus" type="selection" width="55" align="center"/>
      <el-table-column type="index" label="序号" width="50" align="center"/>
      <el-table-column prop="USERNAME" label="用户名" align="center"/>
      <el-table-column prop="NAME" label="姓名" align="center"/>
      <el-table-column prop="DEPARTMENT_NAME" label="部门" align="center"/>
      <el-table-column prop="STATUS" label="培训状态" align="center">
        <template slot-scope="{row}">
          <span v-if="row.STATUS === 0">未培训</span>
          <span v-if="row.STATUS === 1">培训中</span>
          <span v-if="row.STATUS === 2">
            <template v-if="row.TRAIN_STATUS === '0'">
              已培训(不合格)
            </template>
            <template v-else>
              已培训(合格)
            </template>
          </span>
          <span v-if="row.STATUS === 9">申请中</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="{row}">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleShow(row)">详情</el-button>
          <el-button
            v-if="row.STATUS === 2 && row.TRAIN_STATUS === '1'"
            type="success"
            icon="el-icon-edit"
            size="mini"
            @click="getUserInfo(row)">电子合格证
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div>
        <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">培训申请</el-button>
        <el-button type="success" icon="el-icon-finished" plain @click="showRecord">申请记录</el-button>
      </div>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList"/>
    </div>

    <apply ref="apply" :corp-info="SUPERVISE_CORPINFO_ID" @finish="getQuery"/>

    <el-dialog
      v-if="userInfoDialog"
      :visible.sync="userInfoDialog"
      :append-to-body="true"
      title="查看"
      width="60%">
      <table class="table-ui" style="margin-bottom: 20px;">
        <div class="level-title">
          <h1>人员信息</h1>
        </div>
        <tr>
          <th>照片</th>
          <td>
            <span v-if="imgUrl != ''">
              <div class="img-flex">
                <viewer>
                  <img :src="imgUrl" width="40" height="40" style="object-fit: cover;">
                </viewer>
              </div>
            </span>
            <span v-else/>
          </td>
          <th>姓名</th>
          <td>{{ userDetailForm.NAME }}</td>
          <th>性别</th>
          <td>{{ userDetailForm.SEX === '0' ? '男' : '女' }}</td>
        </tr>
        <tr>
          <th>出生年月</th>
          <td>{{ userDetailForm.DATE_OF_BIRTH }}</td>
          <th>年龄</th>
          <td>{{ userDetailForm.AGE }}</td>
          <th>手机号</th>
          <td>{{ userDetailForm.PHONE }}</td>
        </tr>
        <tr>
          <th>身份证</th>
          <td>{{ userDetailForm.CARD_ID }}</td>
          <th>身份证照片</th>
          <!--if条件不可删除-->
          <td v-if="userCardIDPhotoFile.length>0" colspan="3">
            <span>
              <div class="img-flex">
                <viewer>
                  <img
                    v-for="item in userCardIDPhotoFile"
                    :src="config.fileUrl + item.FILEPATH"
                    :key="item.IMGFILES_ID"
                    width="40"
                    height="40"
                    style="object-fit: cover;">
                </viewer>
              </div>
            </span>
          </td>
        </tr>

        <tr>
          <th>民族</th>
          <td>{{ userDetailForm.minzuName ? userDetailForm.minzuName : '暂无信息' }}</td>
          <th>婚姻状况</th>
          <td>{{ userDetailForm.MARITALSTATUS === '0' ? '未婚' : '已婚' }}</td>
          <th>政治面貌</th>
          <td>{{ userDetailForm.zzName }} {{
            userDetailForm.zzName == '中共党员' ? '入党时间' + userDetailForm.POLITICAL_TIME : ''
          }}
          </td>
        </tr>

        <tr>
          <th>户口所在地</th>
          <td>{{ userDetailForm.HKLOCAL ? userDetailForm.HKLOCAL : '暂无信息' }}</td>
          <th>现住址</th>
          <td>{{ userDetailForm.ADDRESS ? userDetailForm.ADDRESS : '暂无信息' }}</td>
          <th>联系电话</th>
          <td>{{ userDetailForm.PHONE }}</td>
        </tr>
        <tr>
          <th>文化程度</th>
          <td>{{ userDetailForm.DEGREE_OF_EDUCATION_NAME }}</td>
          <th>岗位名称(工种)</th>
          <td colspan="5">{{ userDetailForm.POST_ID }}</td>
        </tr>
        <tr>
          <th>是否缴纳社保</th>
          <td :colspan="userDetailForm.IS_SOCIAL === '1' ? '':5">{{ formatLabel(userDetailForm.IS_SOCIAL) }}</td>
          <th v-if="userDetailForm.IS_SOCIAL === '1'">社会保障号码</th>
          <td v-if="userDetailForm.IS_SOCIAL === '1'">{{ userDetailForm.SOCIAL_NUMBER }}</td>
          <th v-if="userDetailForm.IS_SOCIAL === '1'">社保卡照片</th>
          <td v-if="userDetailForm.IS_SOCIAL === '1'&& socialPhotoFile.length>0" colspan="3">
            <span>
              <div class="img-flex">
                <viewer>
                  <img
                    v-for="item in socialPhotoFile"
                    :src="config.fileUrl + item.FILEPATH"
                    :key="item.IMGFILES_ID"
                    width="40"
                    height="40"
                    style="object-fit: cover;">
                </viewer>
              </div>
            </span>
          </td>
        </tr>
        <tr>
          <th>是否参加三级安全培训</th>
          <td>{{ formatLabel(userDetailForm.IS_LEVEL_THREE) }}</td>
          <th v-if="userDetailForm.IS_LEVEL_THREE == 1">三级安全培训照片</th>
          <td v-if="userDetailForm.IS_LEVEL_THREE == 1 && photosOfLevel.length>0" colspan="5">
            <span>
              <div class="img-flex">
                <viewer>
                  <img
                    v-for="item in photosOfLevel"
                    :src="config.fileUrl + item.FILEPATH"
                    :key="item.IMGFILES_ID"
                    width="40"
                    height="40"
                    style="object-fit: cover;">
                </viewer>
              </div>
            </span>
          </td>
        </tr>
        <tr>
          <th>是否缴纳保险</th>
          <td>{{ formatLabel(userDetailForm.IS_BF) }}</td>
          <th>是否特殊工种</th>
          <td>{{ formatLabel(userDetailForm.IS_SPECIAL_JOB) }}</td>
          <th>是否流动人员</th>
          <td>{{ formatLabel(userDetailForm.ISFLOW) }}</td>
        </tr>
      </table>
      <div class="level-title">
        <h1>培训记录</h1>
      </div>
      <el-table
        :data="trainRecordList"
        :header-cell-style="{'font-weight': 'bold','color': '#000'}"
        tooltip-effect="dark"
        border
        fit
        highlight-current-row>
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" label="序号" width="50" align="center"/>
        <el-table-column prop="CLASS_NAME" label="班级名称" align="center"/>
        <el-table-column prop="OPENING_TIME" label="开班时间" align="center"/>
        <el-table-column prop="TRAINING_TYPE_NAME" label="培训类型" align="center"/>
        <el-table-column prop="PLACE_NAME" label="培训地点" align="center"/>
        <el-table-column label="培训有效期" align="center">
          <template slot-scope="{row}">
            <span>{{ formatDate(row.VALIDITY_PERIOD_START) }} 至 {{ formatDate(row.VALIDITY_PERIOD_END) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="userDetailForm.IS_SPECIAL_JOB == '1'" class="level-title">
        <h1>特种作业人员信息</h1>
      </div>
      <table v-for="(item,index) in specialUsersList" :key="index" class="table-ui" style="margin-bottom: 20px;">
        <tr>
          <th style="width: 150px">证书名称</th>
          <td style="width: 150px">{{ item.CERTIFICATE }}</td>
          <th style="width: 150px">作业类别</th>
          <td style="width: 180px">{{ item.SPECIAL_TYPE_NAME }}</td>
          <th style="width: 150px">操作项目</th>
          <td>{{ item.OPERATION_TYPE_NAME }}</td>
        </tr>
        <tr>
          <th>特种作业证书编号</th>
          <td>{{ item.SPECIAL_NUMBER }}</td>
          <th>发证机关</th>
          <td colspan="3">{{ item.ISSUING_AUTHORITY }}</td>
        </tr>
        <tr>
          <th>复审时间</th>
          <td>{{ item.REVIEW_TIME }}</td>
          <th>有效期</th>
          <td colspan="3">{{ item.VALIDITY_TIME_START }} 至 {{ item.VALIDITY_TIME_END }}</td>
        </tr>
      </table>
      <div
        v-if="detailForm.SUPERVISION_STATE === 0 || detailForm.MANAGER_STATE === 0 || detailForm.TERRITORIALITY_STATE === 0"
        class="level-title mt-20">
        <h1>打回信息</h1>
      </div>
      <table
        v-if="detailForm.SUPERVISION_STATE === 0 || detailForm.MANAGER_STATE === 0 || detailForm.TERRITORIALITY_STATE === 0"
        class="table-ui"
        style="margin-bottom: 20px;">
        <tr>
          <th>打回人</th>
          <td v-if="detailForm.SUPERVISION_STATE === 0">{{ detailForm.SUPERVISION_USER_NAME }}</td>
          <td v-if="detailForm.MANAGER_STATE === 0">{{ detailForm.MANAGER_USER_NAME }}</td>
          <td
            v-if="detailForm.TERRITORIALITY_STATE === 0 && detailForm.MANAGER_USER_NAME !== detailForm.TERRITORIALITY_USER_NAME">
            {{ detailForm.TERRITORIALITY_USER_NAME }}
          </td>
          <th>打回原由</th>
          <td v-if="detailForm.SUPERVISION_STATE === 0">{{ detailForm.SUPERVISION_OPINION }}</td>
          <td v-if="detailForm.MANAGER_STATE === 0">{{ detailForm.MANAGER_OPINION }}</td>
          <td
            v-if="detailForm.TERRITORIALITY_STATE === 0 && detailForm.MANAGER_USER_NAME !== detailForm.TERRITORIALITY_USER_NAME">
            {{ detailForm.TERRITORIALITY_OPINION }}
          </td>
        </tr>
      </table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userInfoDialog = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="QRCodeDialog" title="查看二维码" width="680px" class="top-dialog">
      <div class="table-qrcode" style="text-align: center;padding-top: 30px;">
        <vue-qr :text="qrcodeStr" :margin="0" :size="300" color-dark="#000" color-light="#fff"/>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="QRCodeDialog = false">关 闭</el-button>
      </div>
    </el-dialog>
    <user ref="userInfo" append-to-body/>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import vueQr from 'vue-qr'
import apply from './apply'
import dateformat from '@/utils/dateformat'
import user from './user.vue'

export default {
  components: { Pagination, apply, vueQr, user },
  directives: { waves },
  data() {
    return {
      config: config,
      userInfoDialog: false,
      QRCodeDialog: false,
      qrcodeStr: '',
      userDetailForm: {},
      specialUsersList: {},
      detailForm: {},
      userEntryForm: {},
      imgUrl: '',
      SUPERVISE_CORPINFO_ID: '',
      wenhuachengduList: [], // 文化程度
      postList: [], // 岗位名称
      photosOfLevel: [], // 三级教育照片
      trainRecordList: [], // 培训记录
      contractFileList: [], // 合同文件
      insuranceFileList: [], // 保险文件
      gongshangbaoxianFile: [],
      userPhotoFile: [], // 头像
      userCardIDPhotoFile: [], // 身份证照片
      socialPhotoFile: [], // 身份证照片
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      varList: [],
      KEYWORDS: '',
      statusList: [{ value: 0, label: '未培训' }, { value: 1, label: '培训中' }, {
        value: 2,
        label: '已培训(合格)'
      }, { value: 3, label: '已培训(不合格)' }, { value: 9, label: '申请中' }],
      STATUS: '',
      add: false,		// 新增按钮
      del: false,		// 删除按钮
      edit: false	// 修改按钮
    }
  },
  created() {
    this.getSuperviseCorpInfo()
    this.getDict()
    this.getList()
    this.hasButton()
  },
  methods: {
    formatDate(date, column) {
      if (date) {
        return dateformat(date, 'YYYY-MM-DD')
      } else {
        return ''
      }
    },
    getSuperviseCorpInfo() {
      requestFN(
        '/corpinfo/goEdit',
        { CORPINFO_ID: JSON.parse(sessionStorage.getItem('user')).CORPINFO_ID }
      ).then((data) => {
        this.SUPERVISE_CORPINFO_ID = data.pd.SUPERVISE_CORPINFO_ID
      }).catch((e) => {
      })
    },
    // 用户状态为未培训时，才能勾选
    handleSelectWithDifferentStatus(row, rowIndex) {
      if (row.STATUS === 0) {
        // 不禁用
        return true
      } else {
        // 禁用
        return false
      }
    },
    getQuery() {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection()
      }
      this.listQuery = {
        page: 1,
        limit: 10
      }
      this.getList()
    },
    goKeyReset() {
      this.KEYWORDS = ''
      this.STATUS = ''
      this.getQuery()
    },
    getList() {
      this.listLoading = true
      requestFN(
        '/trainingbatch/userList?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          STATUS: this.STATUS
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
      })
        .catch((e) => {
          this.listLoading = false
        })
    },
    // 二维码
    showQRCode(id) {
      this.QRCodeDialog = true
      const arr = [{ USER_ID: id, CODE_TYPE: '1' }]
      this.qrcodeStr = JSON.stringify(arr)
    },
    // 查看
    async handleShow(row) {
      await this.getUserInfoById(row)
      await this.getOtherUserInfoById(row.USER_ID)
      this.userInfoDialog = true
    },
    getUserInfo(row) {
      this.$refs.userInfo.init(row)
    },
    getOtherUserInfoById(id) {
      return new Promise((resolve, reject) => {
        requestFN(
          '/user/getFloatPersonDetailById',
          {
            USER_ID: id,
            CORPINFO_ID: JSON.parse(sessionStorage.getItem('user')).CORPINFO_ID
          }
        ).then((data) => {
          this.userEntryForm = Object.assign(this.userEntryForm, data.eCard)
          this.detailForm = Object.assign(this.detailForm, data.userDetail)
          this.trainRecordList = data.recordList
          resolve()
        }).catch((e) => {
          reject()
        })
      })
    },
    getUserInfoById(row) {
      return new Promise((resolve, reject) => {
        requestFN(
          'user/getDetailByUserIdAndCorpInfoId',
          {
            USER_ID: row.USER_ID,
            CORPINFO_ID: JSON.parse(sessionStorage.getItem('user')).CORPINFO_ID,
            CER_TYPE: '7498057c4c1f4a11b9a960e66ea04a7a'
          }
        ).then((data) => {
          Object.assign(this.userDetailForm, data.pd)
          this.userPhotoFile = data.userPhotoFile
          if (this.userPhotoFile.length > 0) {
            this.imgUrl = config.fileUrl + this.userPhotoFile[0].FILEPATH
          }
          this.photosOfLevel = data.photosOfLevel
          this.specialUsersList = data.specialUsers
          this.insuranceFileList = data.insuranceFile
          this.contractFileList = data.contractFile
          this.userCardIDPhotoFile = data.userCardIDPhotoFile
          this.socialPhotoFile = data.socialPhotoFile
          this.gongshangbaoxianFile = data.gongshangbaoxianFile
          // qr内容初始化
          if (row.STATUS === '2') {
            this.qrCodeStr = config.messageUrl + '?USER_ID=' + row.USER_ID
          } else {
            this.qrCodeStr = ''
          }

          console.log(this.qrCodeStr)
          resolve()
        }).catch((e) => {
          reject()
        })
      })
    },
    // 转换是否
    formatLabel(value) {
      if (value == '1') {
        return '是'
      } else if (value == '0') {
        return '否'
      } else {
        return ''
      }
    },
    handleAdd() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '未勾选培训人员...',
          type: 'error'
        })
        return false
      }

      var users = []
      _selectData.map(item => {
        if (item.STATUS === 0) {
          users.push(item.USER_ID)
        }
      })

      if (users == null || users.length == 0) {
        this.$message({
          message: '勾选人员暂无法提交申请...',
          type: 'error'
        })
        return false
      }
      this.$refs.apply.init(users)
    },

    showRecord() {
      this.$parent.SUPERVISE_CORPINFO_ID = this.SUPERVISE_CORPINFO_ID
      this.$parent.activeName = 'record'
    },

    hasButton() {
      var keys = 'trainingbatch:add,trainingbatch:del,trainingbatch:edit,fhSms,email,fromExcel,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys, tm: new Date().getTime()
        }
      ).then((data) => {
        if (data.result == 'success') {
          this.add = data.trainingbatchfhadminadd	// 增
          this.del = data.trainingbatchfhadmindel	// 删
          this.edit = data.trainingbatchfhadminedit	// 改
          this.fromExcel = data.fromExcel	// 从excel导入权限
          this.toExcel = data.toExcel		// 导出到excel权限
        } else if (data.result == 'exception') {
          // showException('按钮权限', data.exception)// 显示异常
          console.info('按钮权限:', data.exception)
        }
      })
        .catch((e) => {
          this.listLoading = false
        })
    },
    // 获取数据字典数据
    getDict: function() {
      requestFN(
        'dictionaries/getLevels',
        { DICTIONARIES_ID: 'd7d80f08d73a4accbccf4fd3d8d1d867' }
      ).then((data) => {
        this.wenhuachengduList = data.list
      }).catch((e) => {
        this.listLoading = false
      })
      requestFN(
        'dictionaries/getLevels',
        { DICTIONARIES_ID: '09e36ac01e9540f8bc84eab1c1a78754' }
      ).then((data) => {
        this.postList = data.list
      }).catch((e) => {
        this.listLoading = false
      })
    }
  }
}
</script>

