<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <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
                @keyup.enter.native="handleQuery"
                maxlength="20"
            />
        </el-form-item>
        <el-form-item  prop="taskStatusText">
            <el-select
                clearable
                filterable
                style="width: 240px"
                placeholder="状态筛选"
                v-model="queryParams.taskStatusText"
            >
                <el-option
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                    v-for="dict in taskStatusList"
                />
            </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
                    size="mini"
                    :disabled="multiple"
                    @click="acceptancePurchase"
                >
                    验收合格
                </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>
        </el-row>


      <el-table v-loading="loading" :data="tableList" ref="multipleTable" row-key="taskId" @selection-change="handleSelectionChange" border>
        <!-- <el-table-column type="selection" width="55" align="center" :reserve-selection="true" :selectable="selectable"/> -->
        <el-table-column label="序号" align="center" width="50" type="index">
          <template slot-scope="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="到货时间" align="center" prop="arrivalTime" width="90" :show-overflow-tooltip="true"/>
        <el-table-column label="采购单号" align="center" prop="code" width="130" :show-overflow-tooltip="true"/>
        <el-table-column label="物资名称" align="center" prop="purchaseMaTypeName" min-width="140" :show-overflow-tooltip="true"/>
        <el-table-column label="采购数量" align="center" prop="purchaseMaNumber" width="80" :show-overflow-tooltip="true"/>
        <el-table-column label="采购价格(元含税)" align="center" prop="purchaseTaxPrice" width="100" :show-overflow-tooltip="true"/>
        <el-table-column label="采购价格（元不含税）" align="center" prop="purchasePrice" width="100" :show-overflow-tooltip="true"/>
        <el-table-column label="税率" align="center" width="60" prop="taxRate" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                <span>{{ scope.row.taxRate }}%</span>
            </template>
        </el-table-column>
        <el-table-column label="物资厂家" align="center" prop="supplier"  width="120"  :show-overflow-tooltip="true"/>
        <el-table-column label="操作人" align="center" prop="createBy" width="90" :show-overflow-tooltip="true"/>
        <el-table-column label="操作时间" align="center" prop="createTime" width="110" :show-overflow-tooltip="true"/>
<!--        <el-table-column label="状态" align="center" prop="taskStatusText" :show-overflow-tooltip="true" width="100">-->
<!--&lt;!&ndash;            <template slot-scope="scope">&ndash;&gt;-->
<!--&lt;!&ndash;                <dict-tag :options="dict.type.purchase_task_status" :value="scope.row.taskStatus"/>&ndash;&gt;-->
<!--&lt;!&ndash;            </template>&ndash;&gt;-->
<!--        </el-table-column>-->
        <el-table-column label="状态" align="center" prop="taskStatusText" :show-overflow-tooltip="true" width="160">
          <template slot-scope="scope">
        <span v-if="scope.row.taskStatusText == '待验收'">
            <span v-if="scope.row.signLevel == '2'">
                待验收（安全/技术科）
            </span>
            <span v-else-if="scope.row.signLevel == '3'">
                待验收（库管班）
            </span>
            <span v-else>
                待验收
            </span>
        </span>
            <span v-else>
            {{ scope.row.taskStatusText }}
        </span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" width="80" prop="remark" :show-overflow-tooltip="true"/>
        <el-table-column label="操作" align="center" min-width="150" fixed="right">
                        <template slot-scope="scope">
                            <el-button
                                size="mini"
                                @click="handleView(scope.row)"
                            >
                                查看
                            </el-button>
                            <el-button
                                v-if="scope.row.taskStatusName == '未完成'"
                                size="mini"
                                type="primary"
                                @click="handleEdit(scope.row)"
                            >
                                编辑
                            </el-button>
                            <el-button
                                v-if="scope.row.taskStatusName == '未完成'"
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.row)"
                            >
                                删除
                            </el-button>
                            <el-button
                                size="mini"
                                type="primary" v-if="scope.row.taskStatusText == '待验收' && (signLevelDeptMap[scope.row.signLevel] || []).some(name => deptName.includes(name))"
                                @click="handleUpdate(scope.row)"
                            >
                                验收
                            </el-button>
                            <el-button
                                size="mini"
                                type="warning" v-if="scope.row.taskStatusName == '已完成'"
                                @click="handlePrint(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="openPrint" width="1090px" append-to-body>
            <div style="height: 500px; overflow-y: scroll">
                <vue-easy-print tableShow ref="remarksPrintRef" class="print" style="padding: 0 5px;">
                <div id="checkId">
                    <div class="title" style="text-align: center;font-size: 21px;margin-bottom: 15px">
                        到货验收单
                    </div>
                    <div class="info" style="margin: 10px 20px 0; display: flex; justify-content: space-between; flex-wrap: wrap">
                        <div
                            class="item"
                            style="flex-shrink: 0;margin-bottom: 5px;font-size: 14px;max-width: 33%;">
                            <span>生产厂家（供应商）：{{printData.supplier}}</span>
                        </div>
                        <div
                            class="item"
                            style="flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
                            <span>到货日期：{{printData.arrivalDate}}</span>
                        </div>
                        <div class="item" style="flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
                            <span>单据编号：{{printData.code}}</span>
                        </div>
                    </div>
                    <!-- <el-table :data="printTableData" style="margin-top: 20px;width: 100%;" border>
                        <el-table-column label="序号" align="center" type="index" row="2" width="60px"/>
                        <el-table-column label="物资名称" align="center" prop="maTypeName"/>
                        <el-table-column label="规格型号" align="center" prop="typeName"/>
                        <el-table-column label="单位" align="center" prop="unitName"/>
                        <el-table-column label="配送信息" align="center">
                          <el-table-column label="采购数量" align="center" prop="purchaseNum"/>
                           <el-table-column label="验收结论" align="center" prop="checkResult"/>
                           <el-table-column label="质保质量" align="center">
                            <el-table-column label="实收份数" align="center" prop="fileReceiveNum"/>
                            <el-table-column label="符合要求" align="center"/>
                           </el-table-column>
                        </el-table-column>
                        <el-table-column label="备注" align="center" prop="remark"/>
                    </el-table> -->
                    <table border="1" cellspacing="0" cellpadding="4" style="margin-top: 20px;width: 99%;border-collapse: collapse;">
                        <thead>
                            <tr>
                            <th rowspan="3" style="width:60px;">序号</th>
                            <th rowspan="3">物资名称</th>
                            <th rowspan="3">规格型号</th>
                            <th rowspan="3">单位</th>
                            <th colspan="4">配送信息</th>
                            <th rowspan="3">备注</th>
                            </tr>
                            <tr>
                            <th rowspan="2">到货数量</th>
                            <th rowspan="2">验收结论</th>
                            <th colspan="2">质保资料</th>
                            </tr>
                            <tr>
                            <th>实收份数</th>
                            <th>符合要求</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(row, index) in printTableData" :key="index">
                            <td align="center">{{ index + 1 }}</td>
                            <td align="center">{{ row.maTypeName }}</td>
                            <td align="center">{{ row.typeName }}</td>
                            <td align="center">{{ row.unitName }}</td>
                            <td align="center">{{ row.purchaseNum }}</td>
                            <td align="center">{{ row.checkResult }}</td>
                            <td align="center">{{ row.fileReceiveNum }}</td>
                            <td align="center">{{ '符合' }}</td>
                            <td align="center">{{ row.remark }}</td>
                            </tr>
                        </tbody>
                    </table>

                    <div class="fillIn" style="margin-top: 20px;display: flex;justify-content: space-between;" >
                        <div class="item" style="width: 33%;display: flex;align-items: center;">
                            <div style="width: 30%;">供应科：</div>
                            <div style="width: 70%;display: flex;align-items: center;flex-wrap: wrap;" v-if="printData.gySignUrl">
                                <div v-for="(sign, index) in printData.gySignUrl" :key="index" style="width: 35%;margin-left: 5px;">
                                    <img v-if="sign.signUrl" :src="sign.signUrl" :class="sign.signType=='0' ? 'image-type':'sign-type'" alt="">
                                </div>
                            </div>
                        </div>

                        <div class="item" style="width: 33%;display: flex;align-items: center;">
                            <div style="width: 45%;">生产技术科：</div>
                            <div style="width: 55%;display: flex;align-items: center;flex-wrap: wrap;" v-if="printData.scSignUrl">
                                <div v-for="(sign, index) in printData.scSignUrl" :key="index" style="width: 35%;margin-left: 5px;">
                                    <img v-if="sign.signUrl" :src="sign.signUrl" :class="sign.signType=='0' ? 'image-type':'sign-type'" alt="">
                                </div>
                            </div>
                        </div>
                        <div class="item" style="width: 33%;display: flex;align-items: center;">
                            <div style="width: 30%;">库管班：</div>
                            <div style="width: 70%;display: flex;align-items: center;flex-wrap: wrap;" v-if="printData.kgSignUrl">
                                <div v-for="(sign, index) in printData.kgSignUrl" :key="index" style="width: 35%;margin-left: 5px;">
                                    <img v-if="sign.signUrl" :src="sign.signUrl" :class="sign.signType=='0' ? 'image-type':'sign-type'" alt="">
                                </div>
                            </div>
                            <!-- <div>
                                <span>库管班：{{printData.warehouseTeam}}</span>
                            </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="openPrint = false">关 闭</el-button>
            </div>
      </el-dialog>


    </div>
  </template>

  <script>
  import { getPurchaseList,acceptOuterVerify,getPurchaseCheckFormByTaskId } from "@/api/purchase/goodsAccept";
  import { purchaseCheckInfoRemove } from "@/api/purchase/goodsArrived"
  import { downloadFile } from '@/utils/download'
  import { getToken } from '@/utils/auth'
  import vueEasyPrint from "vue-easy-print";
  import printJS from 'print-js';
  export default {
    name: "GoodsAccept",
    dicts: ['purchase_task_status'],
    components: { vueEasyPrint },
    data() {
      return {
        // 遮罩层
        loading: false,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        showHouse: false,
        dateRange:[],
        taskStatusList:[{id:'待验收',name:'待验收'},{id:'待绑定',name:'待绑定'},{id:'待入库',name:'待入库'},{id:'入库中',name:'入库中'},{id:'已入库',name:'已入库'}],
        ids:[],
        // 总条数
        total: 0,
        //表格数据
        tableList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          keyWord:undefined,
          isFinish:undefined,
          startTime: undefined,
          endTime: undefined,
          taskStatusText:undefined
        },
        openPrint: false,
        printData: {},
        printTableData: [],
        deptName: sessionStorage.getItem("deptName"),
        signLevelDeptMap: {
            '2': ['技术科'],
            '3': ['库管', '修试二班']
        }
      };
    },
    activated() {
        if (this.$route.params.isReset) {
            this.resetQuery()
        }
    },
    created() {
        // 设置默认状态为第一个选项（未完成）
        if (this.taskStatusList.length > 0) {
            this.queryParams.taskStatusText = this.taskStatusList[0].id
        }
        this.initDefaultDate();
        this.getList();

    },
    methods: {
        //是否可用勾选框
        selectable(row) {
            console.log(row)
            if (row.taskStatusName == '未完成') {
                return true
            } else {
                return false
            }
        },
        initDefaultDate() {
          const now=new Date();
          //结束时间为当天日期
          this.queryParams.endTime=this.formatDate(now);
          //开始时间往前推一个月
          const oneMonthAgo =new Date(now);
          oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
          this.queryParams.startTime=this.formatDate(oneMonthAgo);
        },
        //格式转换
        formatDate(date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0')
          return `${year}-${month}-${day}`
        },
        /** 查询列表 */
        getList() {
            this.loading = true;
            // this.queryParams.startTime= this.dateRange ? this.dateRange[0] : ''
            // this.queryParams.endTime= this.dateRange ? this.dateRange[1] : ''
            this.queryParams.taskStage= 2
            getPurchaseList(this.queryParams).then(response => {
                this.tableList = response.data.rows;
                this.total = response.data.total;
                this.loading = false;
            });
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.dateRange=[]
            this.queryParams.keyWord=null;
            this.handleQuery();
        },
        /** 搜索按钮操作 */
        handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.taskId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        handleUpdate(row){
            console.log(row)
            let query = { Id:row.id,taskId: row.taskId,isView:"false" }
            this.$tab.closeOpenPage({
                path: '/purchase/goodsAcceptDetail',
                query,
            })
        },
        //查看
        handleView(row){
            console.log(row)
            let query = { Id:row.id,taskId: row.taskId,isView:"true" }
            // this.$tab.closeOpenPage({
            //     path: '/purchase/goodsAcceptDetail',
            //     query,
            // })
            this.$router.push({
                path: '/purchase/goodsAcceptDetail',
                query,
            })
        },
        // 编辑
        handleEdit(row) {
            this.$router.push({
                path: '/purchase/editTools',
                query: { taskId: row.taskId, id: row.id }
            })
        },
        // 删除
        handleDelete(row) {
            this.$modal.confirm('是否确认删除?').then(async () => {
                await purchaseCheckInfoRemove(row.id)
                this.getList()
                this.$modal.msgSuccess('删除成功')
            })
        },
        //批量合格
        acceptancePurchase(){
            let param={
                taskIds:this.ids,
                status:3,
                checkResult:"合格"
            }
            acceptOuterVerify(param).then((response) => {
                if(response.code==200){
                    this.$modal.msgSuccess('操作成功')
                }else{
                    this.$modal.msgSuccess('操作失败')
                }
                this.getList()
                this.$refs.multipleTable.clearSelection()
          }).catch(() => {
                this.$modal.msgError('操作失败')
          })
        },
        //查看验收单
        handlePrint(row) {
            // this.query.taskId = row.taskId
            this.getPrintTable(row.taskId)
            this.openPrint = true
            this.title = '到货验收单'
        },
        //获取验收单数据
        getPrintTable(taskId) {
          getPurchaseCheckFormByTaskId(taskId).then((response) => {
                this.printData = response.data
                this.printTableData = response.data.materialList
                // let supplierList = []
                // this.printTableData.forEach((e) => {
                //     if (e.supplier) {
                //         supplierList.push(e.supplier)
                //     }
                // })
                // supplierList = [...new Set(supplierList)]
                // this.supplierStr = supplierList.join(',')
            })
        },
        //打印
        print() {
            console.log('打印')
            this.$refs.remarksPrintRef.print()
        //     printJS({
        //     printable: 'checkId',
        //     type: 'html',
        //     targetStyles: ['*'],
        //     maxWidth:'1400'
        //     // 其他配置选项
        // });
        },
        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/purchase_check_info/export",
                { ...this.queryParams,taskStage: 2 },
                `新购到货验收_${currentTime}.xlsx`
            );
        },


    }
  };
  </script>
  <style lang="scss" scoped>
  .image-type {
    /* 旋转图片 */
    transform: rotate(-90deg);
    /* 确保旋转后的图片不会超出容器 */
    max-width: 100%;
    /* 保持图片的宽高比 */
    width: 40px;
    height: 80px;
  }
  .sign-type{
    width: 80px;
    height: 40px;
  }


  .uploadImg {
    padding-top: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .deviceCode {
      margin-top: 10px;
      padding-bottom: 20px;
      font-size: 18px;
  }
  /* ::v-deep.el-table .fixed-width .el-button--mini {
      width: 60px !important;
      margin-bottom: 10px;
  } */
  //隐藏图片上传框的css
  ::v-deep.disabled {
      .el-upload--picture-card {
          display: none;
      }
  }
  .el-button {
    margin-bottom: 5px;
  }
  </style>
