<template>
    <div class="app-container">
        <el-form :model="queryParams" @submit.native.prevent ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
            <el-form-item label="生产工单" prop="workorderCodeList">
                <el-input
                v-model="queryParams.workorderCodeList"
                placeholder="请输入生产工单"
                type="textarea" :rows="2" resize="none"
                clearable
                @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="编排单号" prop="arrangeCodeList">
                <el-input
                v-model="queryParams.arrangeCodeList"
                placeholder="请输入编排单号"
                type="textarea" :rows="2" resize="none"
                clearable
                @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="物料编码" prop="sapItemCodeList">
                <el-input
                v-model="queryParams.sapItemCodeList"
                placeholder="请输入物料编码"
                type="textarea" :rows="2" resize="none"
                clearable
                @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="物料名称" prop="itemNameList">
                <el-input
                v-model="queryParams.itemNameList"
                placeholder="请输入物料名称"
                type="textarea" :rows="2" resize="none"
                clearable
                @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="工艺编码" prop="seRouteCode">
                <el-input
                v-model="queryParams.seRouteCode"
                placeholder="请输入工艺编码"
                clearable
                @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="状态" prop="statusList">
                <el-select v-model="queryParams.statusList" multiple placeholder="请选择状态" clearable>
                    <el-option
                        v-for="dict in dict.type.se_issue_table_status"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                        ></el-option>
                </el-select>
            </el-form-item>
              <el-form-item label="需求日期" prop="requestDate">
                <el-date-picker clearable v-model="form.requestDate" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选择需求日期">
                </el-date-picker>
              </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="handleSubmit"
            >完成</el-button>
            <el-button
                size="mini"
                plain
                type="primary"
                :disabled="multiple"
                icon="el-icon-edit"
                @click="handleSend()"
            >发料</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="informationList" :summary-method="getSummaries" show-summary @selection-change="handleSelectionChange" :max-height="maxHeight">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="组合单号" align="center" prop="combinationCode" />
        <el-table-column label="编排单号" align="center" prop="arrangeCode" />
        <el-table-column align="center" prop="workorderCode" width="180">
            <template slot="header" slot-scope="scope">
            <div class="t-cell">
                生产工单
                <span class="t-caret-warpper">
                <i class="t-sort-caret ascend" :class="[ascOrderKeyList.includes('workorderCode') ? 'ascending' : '' ]" @click="handleSortChange('workorderCode', 'asc')"></i>
                <i class="t-sort-caret descend" :class="[descOrderKeyList.includes('workorderCode') ? 'descending' : '' ]" @click="handleSortChange('workorderCode', 'desc')"></i>
                </span>
            </div>
            </template>
        </el-table-column>
        <el-table-column align="center" prop="status" width="100">
            <template slot-scope="scope">
            <dict-tag :options="dict.type.se_issue_table_status" :value="scope.row.status"/>
            </template>
            <template slot="header" slot-scope="scope">
            <div class="t-cell">
                状态
                <span class="t-caret-warpper">
                <i class="t-sort-caret ascend" :class="[ascOrderKeyList.includes('status') ? 'ascending' : '' ]" @click="handleSortChange('status', 'asc')"></i>
                <i class="t-sort-caret descend" :class="[descOrderKeyList.includes('status') ? 'descending' : '' ]" @click="handleSortChange('status', 'desc')"></i>
                </span>
            </div>
            </template>
        </el-table-column>
        <el-table-column align="center" prop="sapItemCode" width="180">
            <template slot="header" slot-scope="scope">
            <div class="t-cell">
                物料编码
                <span class="t-caret-warpper">
                <i class="t-sort-caret ascend" :class="[ascOrderKeyList.includes('sapItemCode') ? 'ascending' : '' ]" @click="handleSortChange('sapItemCode', 'asc')"></i>
                <i class="t-sort-caret descend" :class="[descOrderKeyList.includes('sapItemCode') ? 'descending' : '' ]" @click="handleSortChange('sapItemCode', 'desc')"></i>
                </span>
            </div>
            </template>
        </el-table-column>
        <el-table-column label="物料名称" align="center" prop="itemName" min-width="200"/>
        <el-table-column label="数量" align="center" prop="quantity" />
        <el-table-column align="center" prop="seRouteCode" width="180">
            <template slot="header" slot-scope="scope">
            <div class="t-cell">
                工艺编码
                <span class="t-caret-warpper">
                <i class="t-sort-caret ascend" :class="[ascOrderKeyList.includes('seRouteCode') ? 'ascending' : '' ]" @click="handleSortChange('seRouteCode', 'asc')"></i>
                <i class="t-sort-caret descend" :class="[descOrderKeyList.includes('seRouteCode') ? 'descending' : '' ]" @click="handleSortChange('seRouteCode', 'desc')"></i>
                </span>
            </div>
            </template>
        </el-table-column>
        <el-table-column label="工艺描述" align="center" prop="seRouteDesc" />
        <el-table-column label="油墨重量（KG）" align="center" prop="printinginkCoefficient">
          <template slot-scope="scope">
            <span>{{ scope.row.printinginkCoefficient ? scope.row.quantity * scope.row.printinginkCoefficient : 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="粒子重量（KG）" align="center" prop="particleCoefficient">
          <template slot-scope="scope">
            <span>{{ scope.row.particleCoefficient ? (scope.row.quantity * scope.row.particleCoefficient > 0 ? (scope.row.quantity * scope.row.particleCoefficient).toFixed(3) : 0) : 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="requestDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.requestDate, "{y}-{m}-{d}") }}</span>
          </template>
          <template slot="header" slot-scope="scope">
            <div class="t-cell">
                需求日期
                <span class="t-caret-warpper">
                <i class="t-sort-caret ascend" :class="[ascOrderKeyList.includes('requestDate') ? 'ascending' : '' ]" @click="handleSortChange('requestDate', 'asc')"></i>
                <i class="t-sort-caret descend" :class="[descOrderKeyList.includes('requestDate') ? 'descending' : '' ]" @click="handleSortChange('requestDate', 'desc')"></i>
                </span>
            </div>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
            <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                v-if="!scope.row.status || scope.row.status == 3"
                @click="handleCancel(scope.row)"
            >取消</el-button>
            <el-button
                size="mini"
                type="text"
                v-if="scope.row.status == 4"
                @click="handleunCancel(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 :title="title" :visible.sync="open" width="900px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules"
                label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="申请号" prop="applyNo">
                            <el-input v-model="form.applyNo" placeholder="请输入申请号" disabled />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="工作中心" prop="workstationCode">
                            <el-input v-model="form.workstationCode" placeholder="工作中心">
                                <el-button slot="append" icon="el-icon-search" @click="handleWorkstationSelect"
                                    :disabled="form.workstationMaterialId"></el-button>
                            </el-input>
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="工单号" prop="workorderCode">
                            <el-input v-model="form.workorderCode" disabled>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="申请时间" prop="createTime">
                            <el-date-picker clearable v-model="form.createTime" type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择申请时间" disabled>
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <WorkstationSelect ref="workstationSelect"
                        @onSelected="onWorkstationSelect"></WorkstationSelect>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="需求日期" prop="startTime">
                            <el-date-picker clearable v-model="form.startTime" type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择需求日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="预计结束时间" prop="endTime">
                            <el-date-picker clearable v-model="form.endTime" type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择需预计结束时间" >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-divider content-position="center">申请单物料</el-divider>
            <el-card shadow="always" class="box-card">
                <requestIndex v-if="open" ref="materialRequestRef" :quantity="form.requestNum"
                    :id="form.materialRequestId"></requestIndex>
            </el-card>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { addMaterial } from "@/api/mes/pro/material";
import requestIndex from "./components/requestIndex.vue";
import { genCode } from "@/api/system/autocode/rule";
import dayjs from 'dayjs';
import WorkstationSelect from "@/components/workstationSelect/simpletableSingle.vue";
import { listSecrecyissue, putSecrecyissue, cancelSecrecyissue, uncancelSecrecyissue } from "@/api/mes/pro/secretSend";
export default {
    dicts: ['se_issue_table_status'],
    components: { requestIndex,WorkstationSelect },
    name: "secretSend",
    computed: {
    maxHeight() {
        return window.document.documentElement.clientHeight - 310;
      },
    },
    data() {
        return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 异常信息表格数据
        informationList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        selectRows: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          itemNameList: null,
          statusList: [],
          seRouteCode: null,
          sapItemCodeList: null,
          arrangeCodeList: null,
          abnormalType: null,
          workorderCodeList: null,
          requestDate: null,
        },
        // 表单参数
        form: {},
        ascOrderKeyList: [],
        descOrderKeyList: [],
        // 表单校验
        rules: {
                taskCode: [
                    { required: true, message: "任务单号称不能为空", trigger: "blur" }
                ],
                arrangeCode: [
                    { required: true, message: "编排单号称不能为空", trigger: "blur" }
                ],
                createTime: [
                    { required: true, message: "编排单号称不能为空", trigger: "blur" }
                ],
            }
        };
    },
    created() {
        this.getList();
    },
    methods: {
        handleSortChange(code, type) {
            const ascIndex = this.ascOrderKeyList.indexOf(code);
            const descIndex = this.descOrderKeyList.indexOf(code);
            if(ascIndex != -1) {
                this.ascOrderKeyList.splice(ascIndex, 1);
            }
            if(type == "asc" && ascIndex == -1) {
                this.ascOrderKeyList.push(code);
            }
            if(descIndex != -1) {
                this.descOrderKeyList.splice(descIndex, 1);
            }
            if(type == "desc" && descIndex == -1) {
                this.descOrderKeyList.push(code);
            }
            this.getList();
        },
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    {
                        const itemList = this.$refs.materialRequestRef.tableData;
                        const params = {
                            ... this.form,
                            itemList,
                            secrecyIssueCodes: this.form.secrecyIssueCodes
                        }
                        addMaterial(params).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        getList() {

            this.loading = true;
            const params = {
                ...this.queryParams,
                ascOrderKeyList: this.ascOrderKeyList,
                descOrderKeyList: this.descOrderKeyList,
                itemNameList: this.queryParams.itemNameList ? this.queryParams.itemNameList.split(/[\n,;，、；。]/).filter(item => item) : null,
                sapItemCodeList: this.queryParams.sapItemCodeList ? this.queryParams.sapItemCodeList.split(/[\n,;，、；。]/).filter(item => item) : null,
                arrangeCodeList: this.queryParams.arrangeCodeList ? this.queryParams.arrangeCodeList.split(/[\n,;，、；。]/).filter(item => item) : null,
                workorderCodeList: this.queryParams.workorderCodeList ? this.queryParams.workorderCodeList.split(/[\n,;，、；。]/).filter(item => item) : null,
            }
            listSecrecyissue(params).then(response => {
                this.informationList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 表单重置
        reset() {
            this.form = {
                abnormalId: null,
                abnormalType: null,
                userId: null,
                userName: null,
                nickName: null,
                workorderCode: null,
                remark: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null      };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        handleSend() {
            console.log('this.selectRows11', this.selectRows)
            const arr1 = this.selectRows.filter( v=> !v.status || v.status == 3)
            if (arr1.length !== this.selectRows.length){
                return this.$modal.msgWarning("发料需要选择未发料的工单");
            }
            const arr = this.selectRows.filter( v=> v.seRouteCode !== this.selectRows[0].seRouteCode)
            if (arr.length) {
                return this.$modal.msgWarning("发料选择的工单需要是同一个工艺编码");
            }
            this.reset();
            this.form.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
            this.form.workorderCode = this.selectRows.map(v => v.workorderCode).join(',')
            this.form.secrecyIssueCodes = this.selectRows.map(v => v.secrecyIssueCode)
            this.open = true;
            this.gCode();
            this.title = "发料申请";
        },
        handleSubmit(row) {
            const ids = row.id ? [row.id] : this.ids;
            this.$modal.confirm('是否完成发料申请？').then(function() {
                return putSecrecyissue({
                status: 1,
                ids: ids
            });
            }).then((res) => {
                if(res.code === 200) {
                    this.getList()
                }
            })
        },
        handleCancel(row) {
            const ids = row.id ? [row.id] : this.ids;
            this.$modal.confirm('是否取消发料申请？').then(function() {
                return cancelSecrecyissue({
                status: 4,
                ids: ids
            });
            }).then((res) => {
                if(res.code === 200) {
                    this.getList()
                }
            })
        },
        handleunCancel(row) {
            const ids = row.id ? [row.id] : this.ids;
            this.$modal.confirm('是否撤回取消发料申请？').then(function() {
                return uncancelSecrecyissue({
                status: 3,
                ids: ids
            });
            }).then((res) => {
                if(res.code === 200) {
                    this.getList()
                }
            })
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.selectRows = selection
            this.ids = selection.map(item => item.id)
            this.single = selection.length!==1
            this.multiple = !selection.length
        },
        getSummaries(param){
          const { columns, data } = param
          const sums = []
          columns.forEach((column, index) => {
            if (index === 1) {
              sums[index] = '总数量'
            // } else if (column.label === '数量') {
            //   const temp = data.reduce((prev, curr) => {
            //     return prev + Number(curr.quantity);
            //   }, 0)
            //   sums[index] =  Number.isInteger(temp) ? temp : temp.toFixed(6);
            } else if (column.label === '油墨重量（KG）') {
              const temp = data.reduce((prev, curr) => {
                if(curr.printinginkCoefficient > 0) {
                  return prev + Number(curr.quantity * curr.printinginkCoefficient);
                } else {
                  return prev + 0
                }
              }, 0)
              sums[index] =  Number.isInteger(temp) ? temp : temp.toFixed(6);
            } else if (column.label === '粒子重量（KG）') {
              const temp = data.reduce((prev, curr) => {
                if(curr.particleCoefficient > 0) {
                  return prev + Number(curr.quantity * curr.particleCoefficient);
                } else {
                  return prev + 0
                }
              }, 0)
              sums[index] =  Number.isInteger(temp) ? temp : temp.toFixed(3);
            } else {
              sums[index] = ''
            }
          })
          return sums
        },
        handleWorkstationSelect() {
            this.$refs.workstationSelect.showFlag = true;
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                workstationMaterialId: null,
                applyNo: null,
                itemId: null,
                taskId: null,
                taskWorkunitId: null,
                applyType: null,
                applyNum: null,
                workorderCode: null,
                pickingReason: null,
                workstationCode: null,
                workstationName: null,
                windCase: null,
                grantNum: null,
                remak: null,
                attr1: null,
                attr2: null,
                attr3: null,
                attr4: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                workunitId: null,
                workunitName: null,
                workunitCode: null,
                startTime: null,
                endTime: null,
                arrangeCode: null,
                itemNameList: null,
                taskCode: null
            };
            this.resetForm("form");
        },
        onWorkstationSelect(row) {
            if (row != undefined && row != null) {
                // this.form.workunitName = row.workunitName
                this.$set(this.form, 'workunitCode', row.workunitCode)
                this.form.workstationId = row.workstationId;
                this.form.workstationCode = row.workstationCode;
                this.form.workstationName = row.workstationName;
            }

        },
        gCode() {
            genCode("WORKSTATION_MATERIAL").then((response) => {
                this.form.applyNo = response;
            });
        },
        onWorkorderSelect(row){
            if (row != undefined && row!= null) {
                this.$set(this.form,'workorderCode',row.workorderCode)
            }
        },
    }
}
</script>
<style lang="scss" scoped>
.t-cell {
  display: inline-block;
  box-sizing: border-box;
  position: relative;
  vertical-align: middle;
  padding-left: 10px;
  padding-right: 10px;
  width: 100%;
  .t-caret-warpper {
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    height: 34px;
    width: 24px;
    vertical-align: middle;
    cursor: pointer;
    overflow: initial;
    position: relative;
    .t-sort-caret {
      width: 0;
      height: 0;
      border: 5px solid transparent;
      position: absolute;
      left: 7px;
    }
    .ascend {
      border-bottom-color: #c0c4cc;
      top: 5px;
    }
    .ascending {
      border-bottom-color: #409eff;
    }
    .descend {
      border-top-color: #c0c4cc;
      bottom: 7px;
    }
    .descending {
      border-top-color: #409eff;
    }
  }
}
</style>