<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="任务编码" prop="taskCode">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.taskCode"-->
      <!--          placeholder="请输入任务编码"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="领料编号" prop="requisitionNumber">
        <el-input
          v-model="queryParams.requisitionNumber"
          placeholder="请输入领料单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="saleOrderNo">
        <el-input
          v-model="queryParams.saleOrderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="领料日期" prop="requisitionDate">
        <el-date-picker clearable
                        v-model="queryParams.requisitionDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择领料日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="单据类型" prop="state">
        <el-select v-model="queryParams.requistionOrdersType" filterable placeholder="请选择任务领料"
                   @change="handleQuery">
          <el-option key="1" label="领料" :value="0"/>
          <el-option key="2" label="退料" :value="1"/>
        </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="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:requisitionOrders:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:requisitionOrders:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:requisitionOrders:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:requisitionOrders:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="requisitionOrdersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="领料单ID" align="center" prop="id"/>-->
      <!--      <el-table-column label="任务编码" align="center" prop="taskCode"/>-->
      <el-table-column label="领料单编号" align="center" prop="requisitionNumber"/>
      <el-table-column label="订单编号" align="center" prop="saleOrderNo"/>
      <el-table-column label="单据类型" align="center" prop="requistionOrdersType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.requistionOrdersType == 0">领料</el-tag>
          <el-tag v-else type="success">退料</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="领料日期" align="center" prop="requisitionDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.requisitionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.requisition_orders_state"
            :value="scope.row.state"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" plain size="small">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button v-show="scope.row.state == 0 || scope.row.state==3" size="mini" type="text"
                           icon="el-icon-edit"
                           @click="submitForApproval(scope.row)" v-hasPermi="['business:requisitionOrders:edit']">提交
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button v-show="scope.row.state == 2 && scope.row.requistionOrdersType == 0" size="mini" type="text"
                           icon="el-icon-edit" @click="requistion(scope.row)"
                           v-hasPermi="['business:requisitionOrders:edit']">领料
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button v-show="scope.row.state == 0 || scope.row.state== 3" size="mini" type="text"
                           icon="el-icon-edit"
                           @click="handleUpdate(scope.row)" v-hasPermi="['business:requisitionOrders:edit']">修改
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button v-show="scope.row.state == 0 || scope.row.state == 3" size="mini" type="text"
                           icon="el-icon-delete"
                           @click="handleDelete(scope.row)" v-hasPermi="['business:requisitionOrders:remove']">删除
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  v-show="scope.row.state == 5|| (scope.row.state ==2 && scope.row.requistionOrdersType == 1)"
                  size="mini" type="text" icon="el-icon-delete" @click="handlePrint(scope.row)">打印单据
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </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 :title="title" :visible.sync="open" width="800px" append-to-body :before-close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单据类型" prop="requistionOrdersType">
              <el-select v-model="form.requistionOrdersType" filterable placeholder="请选择任务领料"
                         :disabled="requistionState" @change="handleRequistionState(form.requistionOrdersType)">
                <el-option key="0" label="领料" :value=0></el-option>
                <el-option key="1" label="退料" :value=1></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="领料任务" prop="taskCode">
              <el-select v-model="form.taskCode" filterable placeholder="请选择任务领料" :disabled="requistionState"
                         @change="handleRequistionState(form.requistionOrdersType)">
                <el-option v-for="item in taskList" :key="item.saleProductsId" :label="item.saleProductsTaskName"
                           :value="item.saleProductsId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="领料日期" prop="requisitionDate">
              <el-date-picker style="width: 100%" v-model="form.requisitionDate" type="date"
                              value-format="yyyy-MM-dd" placeholder="请选择领料日期"
                              :disabled="requistionState"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="领料备注" :disabled="requistionState"/>
        </el-form-item>
        <el-divider content-position="center">物料信息</el-divider>

        <el-row :gutter="10" class="mb8" v-show="!requistionState && !requistionOrdersType">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddRequisitionItems">添加
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteRequisitionItems">删除
            </el-button>
          </el-col>
        </el-row>
        <el-table :style="requistionState?'float: left; width: 80%':requistionOrdersType?'float: left; width: 80%':''"
                  :data="requisitionItemsList" :row-class-name="rowRequisitionItemsIndex"
                  @selection-change="handleRequisitionItemsSelectionChange" ref="requisitionItems">
          <el-table-column type="selection" width="50" align="center" v-if="!requistionState"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料" prop="materialId" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.materialId" filterable placeholder="请选择物料"
                         :disabled="requistionState"
                         @change="handleMaterielInfo(scope)">
                <el-option v-for="mtem in materielList" :key="mtem.id" :label="mtem.materielCode+''+mtem.materielName"
                           :value="mtem.materielCode"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column :label="requistionOrdersType?'预计可退数量/重量':'预计领用数量/重量'" prop="quantity"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.quantity" type="number" placeholder="请输入预计领用数量/重量"
                        :disabled="requistionState"/>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="250" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" :disabled="requistionState"/>
            </template>
          </el-table-column>
        </el-table>
        <div :style="requistionState?'':requistionOrdersType?'':'clear: both'"/>
        <el-table style="float: left;width: 20%" v-show="requistionState || requistionOrdersType"
                  :data="requisitionItemsList" :row-class-name="rowRequisitionItemsIndex"
                  @selection-change="handleRequisitionItemsSelectionChange" ref="requisitionItems">
          <el-table-column :label="requistionOrdersType?'回退数量/重量':'实际领用数量/重量'" prop="actualQuantity"
                           width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.actualQuantity" type="number"
                        :placeholder="requistionOrdersType?'请输入回退数量/重量':'请输入实际领用数量/重量'"/>
            </template>
          </el-table-column>
        </el-table>
        <div style="clear: both"/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <div id="wuliao"></div>
  </div>
</template>

<script>
import {
  listRequisitionOrders,
  getRequisitionOrders,
  delRequisitionOrders,
  addRequisitionOrders,
  updateRequisitionOrders, materialRequisitionTaskList, approvalOrders, getRequisitionOrdersByTaskCode
} from "@/api/huaxian/requisitionOrders";
import {queryMaterielList} from "@/api/tablelist/commonTable";

export default {
  name: "RequisitionOrders",
  dicts: ["approval_process_status", "requisition_orders_state"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedRequisitionItems: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 领料单表格数据
      requisitionOrdersList: [],
      // 领料明细表格数据
      requisitionItemsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        requistionOrdersType: 0,
        requisitionNumber: null,
        saleOrderNo: null,
        requisitionDate: null,
        state: null,
        createById: null,
        updateById: null,
        dataApprovalStatus: null,
        processKey: null,
        taskProcessKey: null,
        taskNodeKey: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskCode: [
          {required: true, message: '请选择任务领料', trigger: 'blur'}
        ],
        requisitionItemsList: {
          materialId: [
            {required: true, message: '请选择任务领料', trigger: 'blur'}
          ],
        }
      },
      // 可领料任务列表
      taskList: [],
      // 物料信息表
      materielList: [],
      // 领料状态 填写实际领料数量
      requistionState: false,
      // 单据类型 false：新增领料 true：退料
      requistionOrdersType: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询领料单列表 */
    getList() {
      this.loading = true;
      listRequisitionOrders(this.queryParams).then(response => {
        this.requisitionOrdersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询可领料任务 */
    getTaskList() {
      materialRequisitionTaskList().then(response => {
        this.taskList = response.rows;
      });
    },
    /** 查询物料信息 */
    getMaterielList() {
      queryMaterielList().then(res => {
        this.materielList = res.data;
      });
    },
    // /** 查询字典（初始化所需数据）*/
    // initDictData() {
    //   getDicts("approval_process_status").then((res) => {
    //     //制定周期跑一次定时任务
    //     console.log("字典中数据", res.data);
    //   });
    // },
    // 处理领用物料信息
    handleMaterielInfo(scope) {
      scope.row.specifications = this.materielList.find(item => item.materielCode == scope.row.materialId).specificationModel
    },
    // 取消按钮
    cancel() {
      console.log("取消按钮")
      this.open = false;
      this.reset();
      // 领料状态
      this.requistionState = false;
      // 单据类型
      this.requistionOrdersType = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskCode: null,
        requisitionNumber: null,
        saleOrderNo: null,
        requisitionDate: null,
        requistionOrdersType: null,
        state: null,
        remark: null,
        createById: null,
        createBy: null,
        createTime: null,
        updateById: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        dataApprovalStatus: null,
        processKey: null,
        taskProcessKey: null,
        taskNodeKey: null
      };
      this.requisitionItemsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 获取领料任务
      this.getTaskList();
      // 获取物料信息
      this.getMaterielList();
      this.reset();
      this.open = true;
      this.title = "添加领料单";
      // 默认领料时间为当前
      this.form.requisitionDate = new Date(new Date().toDateString());
      this.form.requistionOrdersType = 0;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      // 获取领料任务
      this.getTaskList();
      getRequisitionOrders(id).then(response => {
        this.form = response.data;
        // this.taskList.find(item => {
        //     if (
        //       this.requisitionItemsList[0].taskCode == item.saleProductsProductNumber &&// 下单重量
        //       this.requisitionItemsList[0].saleOrderNo == item.saleProductsSaleOrderNo &&// 订单编号
        //       this.requisitionItemsList[0].specifications == item.productionProductSpecifications  // 规格
        //     ) {
        //       this.form.value = item.saleProductsId;
        //     }
        //   }
        // );
        this.requisitionItemsList = response.data.requisitionItemsList;
        this.open = true;
        this.form.taskCode = parseInt(this.form.taskCode);
        this.title = "修改领料单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.requisitionItemsList.length == 0) {
        return this.$message.error("请添加物料信息");
      }
      let state = 0;
      this.requisitionItemsList.forEach(item => {

        if (this.form.requistionOrdersType == 0) {
          if (item.materialId == null || item.materialId == '') {
            console.log("物料信息不能为空")
            state = 1;
          }
          if (item.quantity == null || item.quantity == '') {
            console.log("数量不能为空")
            state = 1;
          }
        } else {
          // 退料
          if (item.actualQuantity == null || item.actualQuantity == '') {
            console.log("实际领料数量不能为空")
            state = 1;
          }
        }
      });

      if (state == 1) {
        return this.$message.error("请完善表单数据");
      }

      return;
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.requisitionItemsList = this.requisitionItemsList;
          // 领取物料任务信息
          let taskInfo = this.taskList.find(item => item.saleProductsId === this.form.taskCode)
          // taskinfo.saleProductsLotNumber, // 生产批号
          // taskinfo.productionProductName  // 下单产品名称
          this.form = {
            ...this.form,
            taskCode: taskInfo.saleProductsId,// 子表下单编号
            saleOrderNo: taskInfo.saleProductsSaleOrderNo,// 订单编号
            specifications: taskInfo.productionProductSpecifications, // 规格
          }
          if (this.form.id != null) {
            this.form.requistionState = this.requistionState
            this.form.state = this.requistionState ? 5 : this.form.state;
            updateRequisitionOrders(this.form).then(response => {
              console.log("请求成功", response);
              this.$modal.msgSuccess(this.requistionState ? "领料成功" : "修改成功");
              this.open = false;
              this.getList();
              this.requistionState = false;
            }).catch(reason => {
              console.log("catch", reason);
              this.$modal.msgSuccess(reason.msg());
            });
          } else {
            // 领料状态（0:待提交、1:审核中、2:已批准、3:未批准、4:已作废、5:已完成）
            this.form.state = 0
            this.form.requisitionNumber = Date.now();
            addRequisitionOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除领料单编号为"' + ids + '"的数据项？').then(function () {
        return delRequisitionOrders(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 提交审核*/
    submitForApproval(row) {
      this.$modal.confirm('是否确认提交领料单编号为"' + row.requisitionNumber + '"的领料？').then(function () {
        let form = {
          ...row,
          state: 1,              // 0=:待提交、1:审核中、2:已批准、3:未批准、4:已作废、5:已完成
          dataApprovalStatus: 0, // 数据审批状态（0:未审批、1:审批中、2:审批通过、3:审批不通过）
        }
        return approvalOrders(form);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("提交成功");
      }).catch(() => {
      });
    },
    /** 领料 */
    requistion(row) {
      this.reset();
      const id = row.id || this.ids
      // 获取领料任务
      this.getTaskList();
      getRequisitionOrders(id).then(response => {
        this.form = response.data;
        this.requisitionItemsList = response.data.requisitionItemsList;
        this.open = true;
        this.form.taskCode = parseInt(this.form.taskCode);
        this.requistionState = true;
        this.title = "实际领用数量";
      });
    },
    /** 领料明细序号 */
    rowRequisitionItemsIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 领料明细添加按钮操作 */
    handleAddRequisitionItems() {
      let obj = {};
      obj.materialId = "";
      obj.quantity = "";
      obj.actualQuantity = "";
      obj.state = "";
      obj.specifications = "";
      obj.colorCode = "";
      obj.remark = "";
      obj.createById = "";
      obj.updateById = "";
      obj.dataApprovalStatus = "";
      obj.processKey = "";
      obj.taskProcessKey = "";
      obj.taskNodeKey = "";
      this.requisitionItemsList.push(obj);
    },
    /** 领料明细删除按钮操作 */
    handleDeleteRequisitionItems() {
      if (this.checkedRequisitionItems.length == 0) {
        this.$modal.msgError("请先选择要删除的领料明细数据");
      } else {
        const requisitionItemsList = this.requisitionItemsList;
        const checkedRequisitionItems = this.checkedRequisitionItems;
        this.requisitionItemsList = requisitionItemsList.filter(function (item) {
          return checkedRequisitionItems.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleRequisitionItemsSelectionChange(selection) {
      this.checkedRequisitionItems = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/requisitionOrders/export', {
        ...this.queryParams
      }, `requisitionOrders_${new Date().getTime()}.xlsx`)
    },
    /**
     * 退料逻辑
     */
    handleRequistionState(type) {
      if (type == 0) {
        // 领料
        this.requisitionItemsList = [];
        this.requistionOrdersType = false;
      } else if (type == 1) {
        // 退料
        this.requistionOrdersType = true;
        if (this.form.taskCode) {
          this.requisitionItemsList = [];
          getRequisitionOrdersByTaskCode(this.form.taskCode).then(res => {
            this.requisitionItemsList = res.data.requisitionItemsList;
            console.log("退料详情：", res);
          }).catch(reason => {
            this.requisitionItemsList = [];
          });
        }
      }
    },
    handlePrint(row) {
      // 打印
      this.reset();
      const id = row.id || this.ids
      // 获取领料任务
      this.getTaskList();

      getRequisitionOrders(id).then(response => {
        let printlnInfo = response.data;

        let requisitionItemsList = response.data.requisitionItemsList;

        materialRequisitionTaskList().then(res => {

          queryMaterielList().then(qes => {
            let materielList = qes.data;

            let taskList = res.rows;

            let titleName = printlnInfo.requistionOrdersType == 0 ? "领料单据" : "退料单据";

            var tableInfo = '';

            for (let i = 0; i < requisitionItemsList.length; i++) {
              tableInfo += `
                          <tr>
                            <td>${i + 1}</td>
                            <td>${requisitionItemsList[i].materialId}${materielList.find(item => item.materialCode == i.materialId).materielName}</td>
                            <td>${requisitionItemsList[i].quantity}</td>
                            <td>${requisitionItemsList[i].remark}</td>
                            <td>${requisitionItemsList[i].actualQuantity}</td>
                          </tr>`
            }
            // 模版
            let printContent = `
      <table style="border: 1px solid black;border-collapse: collapse; text-align: center; width: 100%" border="1px;">
      <tr>
        <td rowspan="2" colspan="6">${titleName}</td>
      </tr>
      <tr></tr>
      <tr>
        <td>类型</td>
        <td>${printlnInfo.requistionOrdersType ? '领料' : '退料'}</td>
        <td>任务</td>
        <td>${taskList.find(item => item.saleProductsId == parseInt(printlnInfo.taskCode)).saleProductsTaskName}</td>
        <td>日期</td>
        <td>${printlnInfo.requisitionDate}</td>
      </tr>
      <tr>
        <td>备注</td>
        <td colspan="5">${printlnInfo.remark}</td>
      </tr>
    </table>
    <div style="text-align: center;margin-bottom: 20px">
      <span style="position: relative;top: 20px; background: white;">物料信息</span>
      <hr style="clear:both;"/>
    </div>
    <table style="border: 1px solid black;border-collapse: collapse;text-align: center;  width: 100%" border="1px;">
      <tr>
        <td>序号</td>
        <td>物料</td>
        <td>预计可退数量/重量</td>
        <td>备注</td>
        <td>回退数量/重量</td>
      </tr>
      ` + tableInfo + `
    </table>`;

            document.body.innerHTML = document.getElementById("wuliao").innerHTML = printContent;
            window.print(); //打印
            window.location.reload();
            return false;
          });
        });
      });
    }
  }
};
</script>
