<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="98px">

      <el-form-item label="生产工单编码" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入生产订单编码" clearable @keyup.enter.native="getList" />
      </el-form-item>

      <el-form-item label="物料编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" clearable @keyup.enter.native="getList" />
      </el-form-item>

      <el-form-item label="物料名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="getList" />
      </el-form-item>

      <el-form-item label="生产时间" prop="feedbackTimeArray">
        <el-date-picker v-model="queryParams.feedbackTimeArray" format="yyyy-MM-dd" type="daterange" clearable range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</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-edit" size="mini" @click="openSyncSapSelect()">
          同步SAP药液工单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="handleEditReport()">
          报工信息维护
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="handleReportSap()">
          报工SAP
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" align="center" />
      <el-table-column label="工单编码" align="center" prop="orderCode" width="130">
        <template slot-scope="scope">
          <el-button type="text" @click="handleOpenRawMaterial(scope.row)">{{ codeFormatter(scope.row.orderCode) }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="物料编码" align="center" prop="materialCode" width="220" >
        <template slot-scope="scope">
          {{ codeFormatter(scope.row.materialCode) }}
        </template>
      </el-table-column>
      <el-table-column label="物料名称" align="center" prop="materialName" width="220" :show-overflow-tooltip="true" />
      <el-table-column label="排产数量" align="center" prop="amount" width="100" />
      <el-table-column label="报工数量" align="center" prop="reportAmount" width="100" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="生产时间" align="center" prop="productionDate" width="100" />
      <el-table-column label="SAP报工状态" align="center" prop="status" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.report_sap_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="SAP报工时间" align="center" prop="sapTime" width="150" >
        parseTime
        <template slot-scope="scope">
          {{parseTime(scope.row.sapTime,'{y}-{m}-{d} {h}:{i}:{s}') }}
        </template>
      </el-table-column>
      <el-table-column label="SAP报工信息" align="center" prop="sapRemark" width="150"  />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="handleOpenRawMaterial(scope.row)">查看配方</el-button>
        </template>
      </el-table-column>
    </el-table>

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


    <el-dialog title="配方原料" :visible.sync="openRawMaterial" width="1200px" v-loading="loadingRawMaterial" append-to-body>
      <el-table :data="detailList" >
        <el-table-column type="index" width="90" align="center" label="序号" />
        <el-table-column label="工单编码" align="center" prop="orderCode" width="130">
          <template slot-scope="scope">
            {{ codeFormatter(scope.row.orderCode) }}
          </template>
        </el-table-column>
        <el-table-column label="物料编码" align="center" prop="materialCode" width="220" >
          <template slot-scope="scope">
            {{ codeFormatter(scope.row.materialCode) }}
          </template>
        </el-table-column>
        <el-table-column label="物料名称" align="center" prop="materialName"/>
        <el-table-column label="需求量" align="center" prop="amount" width="100" />
        <el-table-column label="实际需求量" align="center" prop="inputAmount" width="150" >
          <template slot-scope="scope" >
            <el-input type="number" v-if="showChangeRawMaterial" v-model="scope.row.inputAmount" placeholder="请输入订单数量"/>
            <span v-else>{{scope.row.inputAmount}} </span>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="行号" align="center" prop="itemCode" />
        <el-table-column label="生产时间" align="center" prop="productionDate" width="100" />


      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeOpenRawMaterial">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="同步SAP订单" :visible.sync="openSyncSap" v-loading="loadingRawMaterial" append-to-body>
      <el-form   label-width="80px" >
        <el-form-item label-width="100px" label="生产日期" prop="syncDate">
          <el-date-picker
            v-model="syncDates"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSyncSap">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="openEdit" title="信息维护" width="600px">
      <el-form :rules="editRules" ref="editFormRef" :model="editParams">

        <el-row>
          <el-col :span="24">
            <el-form-item label="工单编码" prop="orderCode">
              <el-input v-model="editParams.orderCode" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="editParams.materialCode" readonly />
            </el-form-item>

          </el-col>
          <el-col :span="16">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="editParams.materialName" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="排产数量" prop="amount">
              <el-input v-model="editParams.amount" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报工数量" prop="reportAmount">
              <el-input v-model="editParams.reportAmount" placeholder="请输入报工数量" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="editParams.unit" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="工时" prop="workTime">
              <el-input v-model="editParams.workTime" placeholder="请输入工时" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用人数量" prop="useNum">
              <el-input v-model="editParams.useNum" placeholder="请输入用人数量" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>

import {
  getMedicationOrderDetailList,
  getMedicationOrderList, reportSapMedication,
  syncMedicationOrder, updateMedication, updateMedicationOrderDetailList
} from "@/api/mes/medication";
import {formatTime} from "@/utils";
import {parseTime} from "@/utils/ruoyi";
import {updateReportWorkW3} from "@/api/mes/reportWork";

export default {
  name: "Medication",
  dicts: [ "report_sap_status"],
  data(){
    return {
      total:0,
      queryParams:{
        pageNum:1,
        pageSize:10,
      },
      syncQueryParams:{

      },
      loading:false,
      list:[],
      detailList:[],
      openRawMaterial:false,
      loadingRawMaterial:true,
      showChangeRawMaterial:true,
      openSyncSap:false,
      syncDates:[
        parseTime(new Date(), '{y}-{m}-{d}'),
        parseTime(new Date(), '{y}-{m}-{d}'),
      ],
      openEdit:false,
      selectRow:[],
      editParams:{},
      editRules: {
        reportAmount: [
          { required: true, message: "报工数量不能为空", trigger: "blur" },
        ],
        workTime: [
          { required: true, message: "工时不能为空", trigger: "blur" },
        ],
        useNum: [
          { required: true, message: "用人数量不能为空", trigger: "blur" },
        ],
      },
    }

  },
  created() {
    this.getList()
  },
  methods:{
    parseTime,
    getList(){
      getMedicationOrderList(this.queryParams).then((res)=>{
        this.list = res.rows
        this.total = res.total
      })
    },
    resetQuery(){

    },
    //编码格式化
    codeFormatter(value) {
      if (value) {
        return Number(value);
      }
    },
    openSyncSapSelect(){
      this.openSyncSap = true
    },
    handleSyncSap(){
      if ( !this.syncDates || this.syncDates.length < 2){
        this.$modal.msgError("请选择正确日期");
        return;
      }
      const loadingInstance = this.$loading({
        lock: true, // 锁定屏幕
        text: '处理中，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      syncMedicationOrder({
        startTime:parseTime(new Date(this.syncDates[0]),'{y}{m}{d}'),
        endTime:parseTime(new Date(this.syncDates[1]),'{y}{m}{d}'),
        factory:localStorage.getItem("USER_POOL_NAME_CURRENT").replace("ds_","")
      }).then(()=>{
        this.getList()
        this.$message.success('操作完成！');
        this.openSyncSap = false
      }).finally(()=>{
        loadingInstance.close();
      })
    },
    handleOpenRawMaterial(item) {
      this.openRawMaterial = true
      this.detailList = []
      getMedicationOrderDetailList({
        orderCode:item.orderCode
      }).then((res)=>{
        console.log(item)
        if (item.status === "1"){
          this.showChangeRawMaterial = false
        }else if (item.status === "0") {
          this.showChangeRawMaterial = true
        }
        this.detailList = res.data
      })

    },
    closeOpenRawMaterial(){
      if (this.showChangeRawMaterial){
        //获取需求量与实际需求量不一样的物料
        const list = []
        for (const detail of this.detailList){
          if ( detail.inputAmount !== detail.amount ){
            list.push(detail)
          }
        }

        if (list.length > 0){
          //更新配方信息
          updateMedicationOrderDetailList(list).then(()=>{
            this.$modal.msgSuccess("操作成功！");
          })
        }

      }

      this.openRawMaterial = false
    },
    handleEditReport(){
      if (this.selectRow.length === 0){
        this.$modal.msgError("请选择数据后再进行维护！");
        return
      }

      if (this.selectRow.length > 1){
        this.$modal.msgError("仅能选择一条进行维护！");
        return
      }

      if(this.selectRow[0].status === "1"){
        this.$modal.msgError("改已报工，无法修改！");
        return
      }
      this.openEdit = true
      this.editParams = this.selectRow[0]
    },
    handleReportSap(){
      if (this.selectRow.length <= 0){
        this.$modal.msgError("请选择需要报工的工单！");
        return;
      }

      this.$modal
        .confirm('是否开始报工')
        .then(() => {

          const loadingInstance = this.$loading({
            lock: true, // 锁定屏幕
            text: '处理中，请稍候...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });

          reportSapMedication(this.selectRow)
            .then(res=>{
              this.getList()
              this.$modal.msgSuccess("操作成功！");
            })
            .finally(()=>{
            loadingInstance.close();
          })
        })
        .catch(() => {});
    },
    handleSelectionChange(selection){
      this.selectRow = selection;
    },
    confirmEdit(){
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          updateMedication(this.editParams).then(res=>{
            this.$modal.msgSuccess("操作成功！");
            this.getList()
            this.openEdit = false
          })

        } else {
          this.$modal.msgError("请将信息填写完整！");
          return false;
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">

</style>
