<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="开始日期"
          @change="() => queryParams.endTime = ''"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item>-</el-form-item>
      <el-form-item prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="结束日期"
          :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
          style="width: 130px"
        />
      </el-form-item>

      <el-form-item prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable
          maxlength="50"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择状态" clearable filterable style="width: 240px">
          <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handlePassAll"
          >通过
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleFailAll"
          >驳回
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableList" row-key="id" @selection-change="handleSelectionChange" border>
      <!-- <el-table-column type="selection" width="55" align="center" :selectable="selectable"/> -->
      <el-table-column
        width="60"
        align="center"
        label="序号"
        type="index"
        :index="indexContinuation(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column label="申请人" align="center" prop="creator" :show-overflow-tooltip="true" />
      <el-table-column
        label="申请时间"
        align="center"
        prop="createTime"
        width="110px"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="申请配件" align="center" prop="partName" :show-overflow-tooltip="true" />
      <el-table-column label="单号" align="center" prop="code" :show-overflow-tooltip="true" />
      <el-table-column label="审核人" align="center" prop="auditor" width="110px" :show-overflow-tooltip="true" />
      <el-table-column label="审核时间" align="center" prop="auditTime" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="taskStatusName" :show-overflow-tooltip="true">
        <!-- <template slot-scope="scope">
          <dict-tag :options="dict.type.repair_task_status":value="scope.row.taskStatus"/>
        </template> -->
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" width="100" prop="remark" :show-overflow-tooltip="true"/> -->
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="scope">
          <el-button size="mini" style="margin-bottom: 10px" type="normal" @click="handleView(scope.row)">
            查看
          </el-button>
          <el-button
            size="mini"
            style="margin-bottom: 10px"
            type="primary"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.taskStatus == '0'"
          >
            审核
          </el-button>
          <el-button size="mini" type="warning" v-if="scope.row.taskStatus == '1'" @click="handleLld(scope.row)">
            领料单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 领料单弹窗 -->
    <el-dialog :visible.sync="open" width="1000px" :title="title" append-to-body v-loading="loading">
      <div style="height: 500px; overflow-y: scroll; padding: 0 20px">
        <!-- <vue-easy-print tableShow ref="remarksPrintRef" class="print"> -->
        <div id="checkId7">
          <div class="title" style="text-align: center; font-weight: 600; font-size: 16px">领料单</div>
          <div class="info" style="margin-top: 10px; display: flex; flex-wrap: wrap">
            <div class="item" style="width: 50%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px">
              <span>领料：</span>
              {{ leaseApplyData.deptName }}
            </div>
            <div class="item" style="width: 50%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px">
              <span>发料单位：</span>
              {{ leaseApplyData.sendDeptName }}
            </div>
            <div class="item" style="width: 50%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px">
              <span>时间：</span>
              <span v-if="leaseApplyData.createTime">{{ leaseApplyData.createTime.split(' ')[0] }}</span>
            </div>
            <div class="item" style="width: 50%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px">
              <span>编号：</span>
              {{ leaseApplyData.code }}
            </div>
          </div>
          <div style="width: 100%; margin-top: 20px">
            <!-- <el-table :data="leaseApplyDetails" class="table" border>
              <el-table-column label="序号" align="center" type="index" width="60px" />
              <el-table-column label="配件类型" align="center" prop="partType" />
              <el-table-column label="配件名称" align="center" prop="partName" />
              <el-table-column label="规格型号" align="center" prop="partModel" />
              <el-table-column label="预领数量" align="center" prop="preNum" />
              <el-table-column label="审核状态" align="center" prop="status">
                <template slot-scope="scope">
                  <div v-if="scope.row.status == '0'" style="color: #e6a23c">
                    {{ '未审核' }}
                  </div>
                  <div v-if="scope.row.status == '1'" style="color: #67c23a">
                    {{ '已审核' }}
                  </div>
                  <div v-if="scope.row.status == '2'" style="color: #f56c6c">
                    {{ '驳回' }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" prop="remark" />
            </el-table> -->
            <table border="1.5" class="table" style="border-collapse: collapse; width: 100%">
              <thead>
                <tr>
                  <th style="width: 60px; text-align: center">序号</th>
                  <th style="text-align: center">配件类型</th>
                  <th style="text-align: center">配件名称</th>
                  <th style="text-align: center">规格型号</th>
                  <th style="text-align: center">预领数量</th>
                  <th style="text-align: center">审核状态</th>
                  <th style="text-align: center">备注</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, index) in leaseApplyDetails" :key="index">
                  <td style="text-align: center">{{ index + 1 }}</td>
                  <td style="text-align: center">{{ row.partType }}</td>
                  <td style="text-align: center">{{ row.partName }}</td>
                  <td style="text-align: center">{{ row.partModel }}</td>
                  <td style="text-align: center">{{ row.preNum }}</td>
                  <td style="text-align: center">
                    <span v-if="row.status == '0'" style="color: #e6a23c">未审核</span>
                    <span v-else-if="row.status == '1'" style="color: #67c23a">已审核</span>
                    <span v-else-if="row.status == '2'" style="color: #f56c6c">驳回</span>
                  </td>
                  <td style="text-align: center">{{ row.remark }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="fillIn" style="margin-top: 50px; display: flex; justify-content: center; gap: 50px">
            <div class="item" style="width: 250px; display: flex; align-items: flex-start; flex-wrap: wrap">
              <div style="width: 30%">审核：</div>
              <div
                style="width: 70%; display: flex; align-items: center; flex-wrap: wrap"
                v-if="approveSignList.length > 0"
              >
                <div
                  style="width: 80%; margin-left: 20px; height: 40px; transform: translateY(-30px)"
                  v-for="(item, index) in approveSignList"
                  :key="index"
                >
                  <img
                    :src="item.outSignUrl"
                    style="width: 40px; height: 90px; max-width: 100%"
                    :style="{ transform: item.outSignType == 0 ? 'rotate(-90deg)' : '' }"
                    alt=""
                  />
                </div>
              </div>
            </div>
            <div class="item" style="width: 250px; display: flex; align-items: flex-start">
              <div style="width: 25%">领料：</div>
              <div
                style="width: 75%; margin-left: 20px; transform: translateY(-30px)"
                v-if="leaseSignInfo.outSignUrl"
              >
                <img
                  :src="leaseSignInfo.outSignUrl"
                  style="width: 40px; height: 90px; max-width: 100%"
                  :style="{ transform: leaseSignInfo.outSignType == 0 ? 'rotate(-90deg)' : '' }"
                  alt=""
                />
              </div>
            </div>
            <!-- <div class="item" style="width: 25%; display: flex; align-items: flex-start">
              <div style="width: 25%">库管：</div>
              <div
                style="width: 75%; display: flex; align-items: center; flex-wrap: wrap; transform: translateY(-30px)"
                v-if="kgSignList.length > 0"
              >
                <div
                  style="width: 80%; margin-left: 20px; height: 40px"
                  v-for="(item, index) in kgSignList"
                  :key="index"
                >
                  <img
                    :src="item.outSignUrl"
                    style="width: 40px; height: 90px"
                    :style="{ transform: item.outSignType == 0 ? 'rotate(-90deg)' : '' }"
                    alt=""
                  />
                </div>
              </div>
            </div>
            <div class="item" style="width: 25%; display: flex; align-items: flex-start">
              <div style="width: 25%">制单：</div>
              <div
                style="width: 75%; margin-left: 20px; transform: translateY(-30px)"
                v-if="leaseSignInfo.outSignUrl"
              >
                <img
                  :src="leaseSignInfo.outSignUrl"
                  style="width: 40px; height: 90px; max-width: 100%"
                  :style="{ transform: leaseSignInfo.outSignType == 0 ? 'rotate(-90deg)' : '' }"
                  alt=""
                />
              </div>
            </div> -->
          </div>
        </div>
        <!-- </vue-easy-print> -->
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="print">打 印</el-button>
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPartLeaseInfoListApi, getPartLeaseByTaskIdApi } from '@/api/part/partLease'
import router from '@/router'
import vueEasyPrint from 'vue-easy-print'
import printJS from 'print-js'
export default {
  name: 'Home',
  dicts: [],
  components: { vueEasyPrint },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //搜索下拉数据
      statusList: [
        { id: '0', name: '待审核' },
        { id: '1', name: '已审核' },
        { id: '2', name: '已驳回' }
      ],
      // 字典表格数据
      tableList: [],
      // 日期范围
      dateRange: [],
      statusDataRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: null, //申请时间
        taskStatus: '',
        keyWord: '',
        startTime: undefined,
        endTime: undefined
      },
      form: {},
      passTemp: [],
      failTemp: [],
      //领料单
      open: false,
      title: '',
      leaseApplyDetails: [],
      leaseApplyData: {}, // 领料单信息
      approveSignList: [], // 审批签字列表
      outSignList: [], // 领料签字列表
      kgSignList: [], // 库管签字列表
      leaseSignInfo: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    //打开领料单
    async handleLld(row) {
      this.leaseApplyData = {}
      this.leaseApplyDetails = []
      this.title = '领料单'
      this.open = true
      this.loading = true
      try {
        const res = await getPartLeaseByTaskIdApi({ taskId: row.taskId })
        console.log('🚀 ~ handleLld ~ res:', res)
        this.leaseApplyDetails = res.data.detailsList
        this.leaseApplyData = res.data.details
        this.leaseApplyData.createTime = row.createTime
        this.leaseApplyData.code = row.code
        this.leaseSignInfo = res.data.leaseSignInfo || {}
        this.kgSignList = res.data.kgSignInfo || []
        this.approveSignList = res.data.approveSignInfo || []
      } catch (error) {
        console.log('🚀 ~ handleLld ~ error:', error)
      } finally {
        this.loading = false
      }
    },
    //打印
    print() {
      // this.$refs.remarksPrintRef.print();
      printJS({
        printable: 'checkId7',
        type: 'html',
        targetStyles: ['*'],
        maxWidth: '1400'
        // 其他配置选项
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.passTemp = []
      this.failTemp = []
      this.ids = selection.map(item => item.taskId)
      selection.forEach(item => {
        this.passTemp.push({ status: '1', taskId: item.taskId })
      })
      selection.forEach(item => {
        this.failTemp.push({ status: '2', taskId: item.taskId })
      })
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    //是否可用勾选框
    selectable(row) {
      if (row.taskStatus == '10' || row.taskStatus == '6') {
        return true
      } else {
        return false
      }
    },
    getList() {
      this.loading = true
      const params = {
        keyWord: this.queryParams.keyWord,
        startTime: this.queryParams.startTime,
        endTime: this.queryParams.endTime,
        pageSize: this.queryParams.pageSize,
        pageNum: this.queryParams.pageNum,
        taskStatus: this.queryParams.taskStatus
      }
      getPartLeaseInfoListApi(params).then(response => {
        this.tableList = response.data.rows
        this.total = response.data.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.time = []
      this.resetForm('queryForm')
      this.queryParams.keyWord = ''
      this.handleQuery()
    },
    /** 通过按钮操作 */
    handlePassAll() {
      if (this.ids.length == 0) {
        this.$alert('请至少勾选一条审核数据', '提示', {
          type: 'warning',
          confirmButtonText: '确定'
        })
      } else {
        // outerAudit(this.passTemp).then((response) => {
        //   if (response.code == 200) {
        //     this.$modal.msgSuccess("通过成功");
        //     router.go(0); // 刷新页面
        //   }
        //   this.getTaskInfo();
        // });
      }
    },
    /** 驳回按钮操作 */
    handleFailAll() {
      if (this.ids.length == 0) {
        this.$alert('请至少勾选一条审核数据', '提示', {
          type: 'warning',
          confirmButtonText: '确定'
        })
      } else {
        // outerAudit(this.failTemp).then((response) => {
        //   if (response.code == 200) {
        //     this.$modal.msgSuccess("驳回成功");
        //     router.go(0); // 刷新页面
        //   }
        //   this.getTaskInfo();
        // });
      }
    },

    /** 查看按钮操作 */
    handleView(row) {
      this.$emit('queryTools', row.taskId, row.id, row)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$emit('addTools', row.taskId, row.id, row)
    },

    /** 导出按钮操作 */
    handleExport() {
      const formatTime = date => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      this.download(
        '/material/part_lease/export',
        {
          ...this.queryParams,
          // startTime: this.queryParams.time && this.queryParams.time[0],
          // endTime: this.queryParams.time && this.queryParams.time[1]
        },
        `配件领用_${currentTime}.xlsx`
      )
    }
  },
  watch: {
    $route: {
      handler(to) {
        if (to.query.keyWord) {
          this.queryParams.keyWord = to.query.keyWord
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
  width: 70px !important;
  margin-bottom: 10px;
}
</style>
