<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">任务编号</label>
        <el-input v-model="query.taskCode" clearable placeholder="任务编号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">任务名称</label>
        <el-input v-model="query.taskName" clearable placeholder="任务名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <!-- <label class="el-form-item-label">文档总页数</label>
        <el-input v-model="query.filePageNum" clearable placeholder="文档总页数" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">文档份数</label>
        <el-input v-model="query.fileRepeatNum" clearable placeholder="文档份数" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" /> -->
        <label class="el-form-item-label">打印机编号</label>
        <el-input v-model="query.printerCode" clearable placeholder="打印机编号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <!-- <label class="el-form-item-label">审批人</label>
        <el-input v-model="query.approvalUser" clearable placeholder="审批人" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" /> -->
        <!-- <label class="el-form-item-label">发起人</label>
        <el-input v-model="query.requestUser" clearable placeholder="发起人" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" /> -->
        <label class="el-form-item-label">目前状态</label>
        <el-select v-model="query.status" clearable placeholder="请选择目前状态" class="filter-item" style="width: 185px" @keyup.enter.native="crud.toQuery">
          <el-option
            v-for="item in dict.print_approval_status"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <rrOperation :crud="crud" />
        <deviceTemp @on-change-device="changeVal" />
        <userTemp @on-change="changeUser" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="600px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="130px">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="form.taskName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="文档总页数" prop="filePageNum">
            <el-input v-model="form.filePageNum" style="width: 370px;" @input="form.filePageNum=form.filePageNum.replace(/[^\d]/g,'')" />
          </el-form-item>
          <el-form-item label="文档份数" prop="fileRepeatNum">
            <el-input v-model="form.fileRepeatNum" style="width: 370px;" @input="form.fileRepeatNum=form.fileRepeatNum.replace(/[^\d]/g,'')" />
          </el-form-item>
          <el-form-item label="打印机" prop="device.id">
            <el-input v-model="form.device.id" style="width: 370px;display: none;" />
            <el-input v-model="form.device.name" placeholder="请选择" style="width: 370px;" readonly="readonly" @click.native="crud.doOpenDevice(form.device)" />
          </el-form-item>
          <div id="files">
            <el-form-item label="上传文件" prop="fileList">
              <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls,.doc,.pdf,.dwg,.dxf,.dwt"
                :before-upload="beforeUpload"
                :auto-upload="true"
                :headers="headers"
                :on-success="handleSuccess"
                :on-error="handleError"
                :on-remove="removeFile"
                :action="fileUploadApi +'?name='+ form.name"
                :file-list="fileList"
              >
                <div class="eladmin-upload"><i class="el-icon-upload" /> 添加文件</div>
              </el-upload>
            </el-form-item>
          </div>
          <el-form-item label="备注">
            <el-input v-model="form.remark" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column :selectable="checkboxT" type="selection" width="55" />
        <el-table-column prop="id" label="文印申请编号" />
        <!-- <el-table-column prop="taskCode" label="任务编号" /> -->
        <el-table-column prop="taskName" label="任务名称" />
        <el-table-column prop="filePageNum" label="文档总页数" />
        <el-table-column prop="fileRepeatNum" label="文档份数" />
        <el-table-column prop="device.code" label="打印机编号" />
        <el-table-column prop="device.name" label="打印机名称" />
        <el-table-column :show-overflow-tooltip="true" prop="device.isCommonPrinter" label="是否是公共打印机">
          <template slot-scope="scope">
            <div v-if="scope.row.device.isCommonPrinter == 1">是</div>
            <div v-if="scope.row.device.isCommonPrinter == 0">否</div>
          </template>
        </el-table-column>
        <el-table-column prop="approvalUser.name" label="审批人" />
        <el-table-column prop="requestUser.name" label="发起人" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ dict.label.print_approval_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column v-if="checkPer(['admin','dmPrintingRequest:edit','dmPrintingRequest:del']) " label="操作" width="150px" align="center">
          <!-- v-if="(scope.row.status === '00' && !scope.row.isHasApproval) || scope.row.status === '01' || scope.row.status === '02' "-->
          <template slot-scope="scope">
            <!-- (scope.row.status === '00' && scope.row.isHasApproval) -->
            <udOperation
              :data="scope.row"
              :disabled-edit="scope.row.status === '01' || scope.row.approvalUser"
              :disabled-dle="scope.row.status === '01' || scope.row.device.isCommonPrinter === '1'"
              :permission="permission"
            />
            <!-- !scope.row.isHasApproval &&  -->
            <el-button
              v-if="scope.row.device.isCommonPrinter === '0' && !scope.row.approvalUser"
              size="mini"
              type="warning"
              icon="el-icon-user"
              @click="crud.doOpenDmUser(scope.row,'approvalUser','选择审批人');changeType('approvalUser')"
            >选择审批人</el-button>
            <!-- scope.row.isHasApproval && scope.row.status === '00' ||  -->
            <el-button
              v-if="scope.row.device.isCommonPrinter === '0' && scope.row.approvalUser"
              size="mini"
              type="warning"
              icon="el-icon-user"
              @click="doRecall(scope.row)"
            >撤回</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import crudDmPrintingRequest from '@/api/dm/printingRequest/dmPrintingRequest'
import { getAllDevice } from '@/api/dm/device/dmDevice'
import { del } from '@/api/tools/localStorage.js'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import deviceTemp from '@/components/Device/index'
import userTemp from '@/components/User/dmUserindex'

const defaultForm = { id: null, taskCode: null, taskName: null, filePageNum: null, fileRepeatNum: null, device: { id: null }, status: null, remark: null, name: '', file: { id: null }}
export default {
  name: 'DmPrintingRequest',
  components: { pagination, crudOperation, rrOperation, udOperation, deviceTemp, userTemp },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['print_approval_status'],
  cruds() {
    return CRUD({ title: '文印申请', url: 'api/dmPrintingRequest', idField: 'id', sort: 'id,desc', tempBtnShow: {
      user: false
    }, selectOne: true, crudMethod: { ...crudDmPrintingRequest }})
  },
  data() {
    return {
      deviceList: [], // 设备集合
      fileList: [], // 文件集合
      deviceId: '', // 设备
      initFileId: '', // 编辑时，存储 添加时的文件id,防止误删
      beforeSubmitFileId: '', // 编辑时，存储 添加时的文件id,防止误删
      tmpType: '', // 弹框所属字段
      openid: '', // 弹框项
      permission: {
        add: ['admin', 'dmPrintingRequest:add'],
        edit: ['admin', 'dmPrintingRequest:edit'],
        del: ['admin', 'dmPrintingRequest:del']
      },
      rules: {
        id: [
          { required: true, message: 'id不能为空', trigger: 'blur' }
        ],
        taskName: [
          { required: true, message: '任务名称不能为空', trigger: 'blur' }
        ],
        filePageNum: [
          { required: true, message: '文档总页数不能为空', trigger: 'blur' }
        ],
        fileRepeatNum: [
          { required: true, message: '文档份数不能为空', trigger: 'blur' }
        ]
        // 'device.id': [
        //   { required: true, message: '打印机不能为空', trigger: 'blur' }
        // ]

      },
      queryTypeOptions: [
        { key: 'taskCode', display_name: '任务编号' },
        { key: 'taskName', display_name: '任务名称' },
        { key: 'filePageNum', display_name: '文档总页数' },
        { key: 'fileRepeatNum', display_name: '文档份数' },
        { key: 'printerCode', display_name: '打印机编号' },
        { key: 'approvalUser', display_name: '审批人' },
        { key: 'requestUser', display_name: '发起人' },
        { key: 'createBy', display_name: '创建者' },
        { key: 'updateBy', display_name: '更新者' },
        { key: 'status', display_name: '目前状态（已通过、未审核、已驳回）' }
      ],
      headers: { 'Authorization': getToken() }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  created() {
    getAllDevice()
    console.info('params', this.fileUploadApi)
  },
  methods: {
    checkboxT(row, rowIndex) {
      return (row.status === '00' && !row.isHasApproval) || row.status === '01' || row.status === '02'
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.beforeToAdd]() {
      this.getDevices()
      this.fileList = []
    },
    [CRUD.HOOK.beforeAddCancel]() {
      // 删除已上传的文件
      if (this.form.file.id != null) {
        this.delFile(this.form.file.id)
      }
    },
    [CRUD.HOOK.beforeEditCancel]() {
      if (this.form.file.id !== this.initFileId) {
        this.delFile(this.form.file.id)
      }
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (crud.form.file === null || crud.form.file.id === null || crud.form.file === undefined || crud.form.file.id === undefined) {
        this.$message({
          message: '文件不能为空',
          type: 'warning'
        })
        return false
      }
      this.fileList.push(crud.form.file.id)
      return true
    },
    [CRUD.HOOK.afterToEdit]() {
      // 回显已上传的文件
      this.fileList = []
      if (this.form.file.path != null) {
        const obj = {}
        obj.response = {}
        this.initFileId = this.form.file.id
        obj.response.id = this.form.file.id
        obj.url = this.form.file.path
        obj.name = this.form.file.name + '.' + this.form.file.suffix
        this.fileList.push(obj)
      }
      this.beforeSubmitFileId = ''
    },
    [CRUD.HOOK.beforeSubmit]() {
      this.beforeSubmitFileId = this.form.file.id
    },
    [CRUD.HOOK.afterSubmit]() {
      // 删除旧文件
      if (this.initFileId && this.beforeSubmitFileId !== this.initFileId) {
        this.delFile(this.initFileId)
      }
      this.$refs.upload.clearFiles()
    },
    getDevices() {
      getAllDevice().then(res => {
        this.deviceList = res
      }).catch(() => { })
    },
    changeDevice(value) {
      this.deviceId = value
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      this.form.file.id = response.id
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    removeFile(file, fileList) {
      if (file.response.id && file.response.id !== this.initFileId) {
        this.delFile(file.response.id)
      }
    },
    changeVal(device, rowid) {
      if (device[0]) {
        this.form.device = device[0]
      }
    },
    delFile(id) {
      del([id]).then(res => {
        this.form.file.id = null
      }).catch(() => { })
    },
    changeType(type) {
      // 确定当前弹框控制的值
      this.tmpType = type
    },
    changeUser(user, rowid) {
      var data = {}
      data['id'] = rowid
      data[this.tmpType + 'List'] = user
      // data[this.tmpType+"List"] = user[0]
      if (this.tmpType === 'approvalUser') {
        crudDmPrintingRequest.addAapprovalUser(data).then(res => {
          this.crud.notify('已添加审批人', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.refresh()
        }).catch(() => { this.crud.notify('失败', CRUD.NOTIFICATION_TYPE.ERROR) })
      }
    },
    doRecall(data) {
      crudDmPrintingRequest.recallApprovalUser(data).then(res => {
        this.crud.notify('已撤回', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.crud.refresh()
      }).catch(() => { this.crud.notify('失败', CRUD.NOTIFICATION_TYPE.ERROR) })
    }
  }
}
</script>

<style scoped>

</style>
