<template>
  <div>
    <el-table :data="tableData" border>
      <el-table-column align="center" label="" width="165">
        <template slot-scope="scope">
          <el-button
            size="mini"
            class="opt-btn"
            icon="el-icon-minus"
            @click="delRow(scope.$index, scope.row)"
          >
          </el-button>
          <el-button
            size="mini"
            class="opt-btn"
            icon="el-icon-bottom"
            :disabled="scope.$index === tableData.length - 1"
            @click="moveDown(scope.$index, scope.row)"
          >
          </el-button>
          <el-button
            size="mini"
            class="opt-btn"
            icon="el-icon-top"
            :disabled="scope.$index === 0"
            @click="moveUp(scope.$index, scope.row)"
          >
          </el-button>
          <el-button
            size="mini"
            class="opt-btn"
            :style="{'visibility': scope.$index === tableData.length - 1 ? '' : 'hidden'}"
            icon="el-icon-plus"
            @click="addRow(scope.$index, scope.row)"
          >
          </el-button>
        </template>
      </el-table-column>
      <el-table-column :label="$t('工序序号')" type="idx" align="center" >
        <template slot-scope="scope">
          {{ ((scope.$index + 1) * 10).toString().padStart(4, '0') }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('工序编码')" prop="processId" align="center" width="140">
        <template slot-scope="scope">
          <el-select v-model="scope.row.processId" filterable :disabled="mode == 'info'"
          @change="(v) => chooseprocessName(v, scope.row, scope.$index)">
            <el-option
              v-for="item in processOptions"
              :key="item.processId"
              :label="item.processCode"
              :value="item.processId"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :label="$t('工序名称')" prop="processName" align="center" width="160">
        <template slot-scope="scope">
          <el-select v-model="scope.row.processId" filterable :disabled="mode == 'info'"
          @change="(v) => chooseprocessName(v, scope.row, scope.$index)">
            <el-option
              v-for="item in processOptions"
              :key="item.processId"
              :label="item.processName"
              :value="item.processId"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.workstation_code')" prop="workstationCode" align="center" width="130">
        <template slot-scope="scope">
          <el-select v-model="scope.row.workstationId" :disabled="mode == 'info'" filterable @change="(v) => chooseworkstationName(v, scope.row, scope.$index)">
              <el-option
                v-for="dict in workstationList"
                :key="dict.workstationId"
                :label="dict.workstationCode"
                :value="dict.workstationId"
              />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.workstation')" prop="workstationId" align="center" width="140">
        <template slot-scope="scope">
          <el-select v-model="scope.row.workstationId" :disabled="mode == 'info'" filterable @change="(v) => chooseworkstationName(v, scope.row, scope.$index)">
              <el-option
                v-for="dict in workstationList"
                :key="dict.workstationId"
                :label="dict.workstationName"
                :value="dict.workstationId"
              />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :label="$t('标准工时')" prop="stdWorkingTime" align="center" width="100">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.stdWorkingTime"
           
            :disabled="mode == 'info'"
            clearable
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('换型时间')" prop="lineBreakTime" align="center" width="100">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.lineBreakTime"
           
            :disabled="mode == 'info'"
            clearable
          />
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('工时单位')"
        prop="stdWorkingTimeUom"
        align="center"
        width="100"
      >
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.stdWorkingTimeUom"
            clearable
            :disabled="mode == 'info'"
           
          >
            <el-option
              v-for="dict in dict.type.mes_work_time"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :label="$t('单价')" prop="unitPrice" align="center" width="165">
        <template slot-scope="scope">
          <el-input-number
            style="width: 140px"
            v-model="scope.row.unitPrice"
            placeholder
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('是否外协')"
        prop="outsourced"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <el-select
              v-model="scope.row.outsourced" v-if="mode !== 'info'"
             
              clearable
            >
              <el-option
                v-for="dict in dict.type.sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          <dict-tag v-else
            :options="dict.type.sys_yes_no"
            :value="scope.row.outsourced"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('计量单位')" prop="unitOfMeasure" align="center" width="100">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.unitOfMeasure"
            :disabled="mode == 'info'"
           
            clearable
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('关键工序')" prop="keyFlag" align="center" width="100">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.keyFlag" v-if="mode !== 'info'"
           
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <dict-tag
            v-else
            :options="dict.type.sys_yes_no"
            :value="scope.row.keyFlag"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('是否质检')" prop="isCheck" align="center" width="100">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.isCheck" v-if="mode !== 'info'"
           
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <dict-tag
            v-else
            :options="dict.type.sys_yes_no"
            :value="scope.row.isCheck"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('工序备注')" prop="processRemark" align="center" width="140">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.processRemark"
            :disabled="mode == 'info'"
           
            clearable
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('图纸上传')" prop="processRemark" align="center" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            :icon="scope.row.drawingList && scope.row.drawingList.length > 0 ? 'el-icon-reading' : 'el-icon-upload'"
            :title="scope.row.drawingList && scope.row.drawingList.length > 0 ? $t('查看文件') : $t('文件上传')"
            @click="openUploadDialog(scope.row, scope.$index)"
          >
          </el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column
        v-if="mode != 'info'"
        :label="$t('common.option')"
        align="center"
        width="300"
        fixed="right"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="text" size="small" @click="openSetProd(row, $index)">
            设置物料
          </el-button>
          <el-button
            type="text"
            size="small"
            @click="openSetQrindex(row, $index)"
          >
            设置检验项
          </el-button>
          <el-button type="text" size="small" @click="openSetTool(row, $index)">
            设置工装量具
          </el-button>
          <el-button type="text" size="small" @click="updateRow(row, $index)"
            >{{ $t('common.edit') }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        v-if="mode == 'info'"
        :label="$t('common.option')"
        align="center"
        width="310"
        fixed="right"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="text" size="small" @click="SearchProd(row, $index)">
            查看物料
          </el-button>
          <el-button
            type="text"
            size="small"
            @click="searchQrindex(row, $index)"
          >
            查看检验项
          </el-button>
          <el-button type="text" size="small" @click="searchTool(row, $index)">
            查看工装量具
          </el-button>
          <el-button type="text" size="small" @click="searchRow(row, $index)"
            >查看工序信息</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <ProcessProd
      :process="currentRow"
      :bomList="bomList"
      ref="ProcessProdRef"
      @updateItem="updateItem"
    />
    <ProcessQcindex :process="currentRow" ref="ProcessQcindexRef" />
    <ProcessTool :process="currentRow" ref="ProcessToolRef" />
    <uploadTuzhi ref="uploadTuzhiRef" :process="currentRow" @updateItem="updateItemUpload" />
    <el-dialog
      v-dialogDrag
      :visible.sync="showFlag"
      width="800px"
      :title="$t('工序设置')"
    >
      <el-form
        ref="form"
        class="page-form"
        :model="form"
        size="small"
        :inline="true"
        label-width="8em"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('common.workstation')" prop="workstationId">
              <el-input
                v-model="form.workstationName"
                disabled
               
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="handleWorkstationSelect"
                ></el-button>
              </el-input>
              <WorkstationSelect
                ref="WorkstationSelect"
                :processId="form.processId"
                @onSelected="onWorkstationSelected"
              ></WorkstationSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('标准工时')" prop="stdWorkingTime">
              <el-input
                type="number"
                v-model="form.stdWorkingTime"
               
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('换型时间')" prop="lineBreakTime">
              <el-input
                type="number"
                v-model="form.lineBreakTime"
               
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('工时单位')" prop="stdWorkingTimeUom">
              <el-select
                v-model="form.stdWorkingTimeUom"
                clearable
               
              >
                <el-option
                  v-for="dict in dict.type.mes_time_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('工序计量单位')" prop="unitOfMeasure">
              <el-input
                v-model="form.unitOfMeasure"
               
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('副单位')" prop="deputyUnitOfMeasure">
              <el-input
                v-model="form.deputyUnitOfMeasure"
               
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('单位转换比例')" prop="unitConvert">
              <el-input
                type="number"
                v-model="form.unitConvert"
               
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('加工方式')" prop="processingMethod">
              <el-select
                v-model="form.processingMethod"
               
                clearable
                style="width: 150px"
              >
                <el-option
                  v-for="dict in dict.type.process_control_code"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="form.processingMethod == 'PP02'">
            <el-col :span="12">
              <el-form-item
                :label="$t('采购信息记录号')"
                prop="procurementInformationId"
              >
                <el-input
                  v-model="form.procurementInformationId"
                 
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('供应商科目编号')" prop="vendorSubjectId">
                <el-input
                  v-model="form.vendorSubjectId"
                 
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('净价')" prop="netPrice">
                <el-input
                  v-model="form.netPrice"
                 
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('采购组织')" prop="procurementOrganization">
                <el-input
                  v-model="form.procurementOrganization"
                 
                ></el-input>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="12">
            <el-form-item :label="$t('关键工序')" prop="keyFlag">
              <el-select
                v-model="form.keyFlag"
               
                clearable
                style="width: 150px"
              >
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('是否质检')" prop="isCheck">
              <el-select
                v-model="form.isCheck"
               
                clearable
                style="width: 150px"
              >
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button type="default" @click="showFlag = false">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>


import {listAllProcess} from "@/api/mes/pro/process";
import {
  getworkstationList} from '@/api/mes/pro/scheduleList'
import ItemBomSelect from "@/components/itemBomSelect/single.vue";
import ProcessProd from "./ProcessProd.vue";
import ProcessQcindex from "./ProcessQcindex.vue";
import ProcessTool from "./ProcessTool.vue";
import uploadTuzhi from "./uploadTuzhi.vue";
import WorkstationSelect from "@/components/workstationSelect/simpletableSingle.vue";
export default {
  components: {
    ItemBomSelect,
    ProcessProd,
    ProcessQcindex,
    ProcessTool,
    uploadTuzhi,
    WorkstationSelect,
  },
  inject: ["mode"],
  dicts: [
    "process_control_code",
    "sys_yes_no",
    "mes_time_type",
    "mes_work_time",
    "product_shape",
  ],
  props: {
    bomList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      /**弹窗状态 */
      showFlag: false,
      /**表格数据 */
      tableData: [],
      workstationList: [],
      breakData: {
        processName: null,
        processId: null,
        processCode: null,
        workstationName: null,
        workstationId: null,
        workstationCode: null,
        stdWorkingTime: null,
        lineBreakTime: null,
        stdWorkingTimeUom: 'SECOND', 
        outsourced: 'N',
        unitOfMeasure: null,
        keyFlag: 'N',
        isCheck: 'N',
        drawingList: []
      },
      processOptions: [],
      loadingProcess: true,
      /**表单规则 */
      rules: {},
      /**表单初始化数据 */
      form: {
        productionSolutionId: "",
        recordId: "",
        processId: "",
        workstationId: "",
        keyFlag: "",
        isCheck: "",
        idx: "",
        workstationCode: "",
        processingMethod: "",
        processName: "",
        processRemark: "",
        quantity: "",
        unitOfMeasure: "",
        employeesNum: "",
        stdWorkingTime: "",
        lineBreakTime: "",
        stdWorkingTimeUom: "SECOND",
        procurementInformationId: "",
        vendorSubjectId: "",
        netPrice: "",
        procurementOrganization: "",
        remark: "",
        deputyUnitOfMeasure: "",
        unitConvert: "",
        sacmForEdgeOpening: '',
               sacmForPasteComposite: '',
               sacmForThermalComposite: '',
               sacmForLabeling: '',
               sacmForBuckleUp: '',
               sacmForCreasing: '',
               sacmForOrgan: '',
               sacmForThermalCutting: '',
               sacmForThermalSelfFusion: '',
               sacmForMolarTooth: '',
               sacmForSlitting: '',
      },
      currentRow: {},
      currentRowIndex: undefined,
    };
  },
  created (){
    this.tableData = [JSON.parse(JSON.stringify(this.breakData))]
    this.getProcess()
    this.hanldeGetworkstationList()
  },
  methods: {
    async hanldeGetworkstationList() {
      const response = await getworkstationList({workshopId: null})
      this.workstationList = response.rows
    },
    //查询工序信息
    getProcess(keyword = null){
      this.loadingProcess = true
      listAllProcess({}).then( response =>{
        this.processOptions = response.data;
        this.loadingProcess = false
      });
    },
    // 上移
    moveUp(index, row) {
      if (index > 0) {
        const upDate = this.tableData[index - 1];
        this.tableData.splice(index - 1, 1);
        this.tableData.splice(index, 0, upDate);
      } else {
        console.log("已经是第一条，不可上移");
      }
    },
    // 下移
    moveDown(index, row) {
      if (index + 1 === this.tableData.length) {
        console.log("已经是最后一条，不可下移");
      } else {
        const downDate = this.tableData[index + 1];
        this.tableData.splice(index + 1, 1);
        this.tableData.splice(index, 0, downDate);
      }
    },
    delRow(index) {
      this.$confirm(this.$t('确定删除这条数据吗'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        if(this.tableData.length > 1) {
          this.tableData.splice(index, 1);
        } else {
          this.$message.warning(this.$t('最后一条数据不可以删除'))
        }
        
      }).catch(() => {
      });
    },
    openUploadDialog(row, idx){
      this.currentRow = row;
      this.currentRowIndex = idx;
      this.$refs["uploadTuzhiRef"].showOpen = true
    },
    addRow(){
      if(!this.tableData[this.tableData.length - 1]['processName']){
        this.$message.warning(this.$t('已经有一条空白数据'))
      } else {
        this.tableData.push(JSON.parse(JSON.stringify(this.breakData)))
      }
    },
    setList(rows) {
      this.tableData = rows.map((item) => {
        return item;
      });
      if(this.mode !== 'info') {
        this.tableData.push(JSON.parse(JSON.stringify(this.breakData)))
      }
    },
    /** 更新工序的物料信息 */
    updateItem(items) {
      this.tableData[this.currentRowIndex].processItemList = items;
    },
    updateItemUpload(items) {
      this.tableData[this.currentRowIndex].drawingList = items;
    },
    openSetProd(row, idx) {
      this.currentRow = row;
      this.currentRowIndex = idx;
      this.$refs["ProcessProdRef"].showProcessProd = true;
    },
    openSetQrindex(row, idx) {
      this.currentRow = row;
      this.currentRowIndex = idx;
      this.$refs["ProcessQcindexRef"].showProcessProd = true;
    },
    openSetTool(row, idx) {
      this.currentRow = row;
      this.currentRowIndex = idx;
      this.$refs["ProcessToolRef"].showProcessProd = true;
    },
    /**查看物料 */
    SearchProd(row, idx) {
      this.currentRow = row;
      this.currentRowIndex = idx;
      this.$refs["ProcessProdRef"].optType = "detail";
      this.$refs["ProcessProdRef"].showProcessProd = true;
    },
    /**查看行 */
    searchRow(row, idx) {
      this.form = Object.assign(this.form, row);
      this.currentRowIdx = idx;
      this.showFlag = true;
    },
    /**查看质检 */
    searchQrindex(row, idx) {
      this.currentRow = row;
      this.currentRowIndex = idx;
      this.$refs["ProcessQcindexRef"].optType = "detail";
      this.$refs["ProcessQcindexRef"].showProcessProd = true;
    },
    /**查看工装 */
    searchTool(row, idx) {
      this.currentRow = row;
      this.currentRowIndex = idx;
      this.$refs["ProcessToolRef"].optType = "detail";
      this.$refs["ProcessToolRef"].showProcessProd = true;
    },
    /**更新行 */
    updateRow(row, idx) {
      Object.assign(this.form, row);
      this.currentRowIndex = idx;
      this.showFlag = true;
    },
    /**表单提交 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.showFlag = false;
          this.tableData.splice(this.currentRowIndex, 1, {
            ...this.currentRow,
            ...this.form,
          });
        }
      });
    },
    getComData() {
      let isNULL = false
      for(let i = 0; i< this.tableData.length; i++) {
        const item = this.tableData[i]
        console.log('item', item)
        if (item.processName && !item.workstationId) {
          this.$message.warning(this.$t('工作中心必选'))
          isNULL = true
          break
        } else if (item.processName && !item.stdWorkingTime) {
          this.$message.warning(this.$t('标准工时必填'))
          isNULL = true
          break
        } else if (item.processName && !item.stdWorkingTimeUom) {
          this.$message.warning(this.$t('工时单位必选'))
          isNULL = true
          break
        }
      }
      if (isNULL) {
        return isNULL
      }
      this.tableData.forEach((item, index) => {
        item['idx'] = ((index + 1) * 10).toString().padStart(4, '0')
      })
      return this.tableData.filter(v => v && v.processName && v.workstationId && v.stdWorkingTime );
    },
    /**重置表单 */
    resetForm() {
      this.form = {
        productionSolutionId: "",
        recordId: "",
        processId: "",
        workstationId: "",
        keyFlag: "",
        isCheck: "",
        idx: "",
        workstationCode: "",
        processingMethod: "",
        processName: "",
        processRemark: "",
        quantity: "",
        unitOfMeasure: "",
        employeesNum: "",
        stdWorkingTime: "",
        lineBreakTime: "",
        stdWorkingTimeUom: "SECOND",
        procurementInformationId: "",
        vendorSubjectId: "",
        netPrice: "",
        procurementOrganization: "",
        remark: "",
        deputyUnitOfMeasure: "",
        unitConvert: "",
        sacmForEdgeOpening: '',
               sacmForPasteComposite: '',
               sacmForThermalComposite: '',
               sacmForLabeling: '',
               sacmForBuckleUp: '',
               sacmForCreasing: '',
               sacmForOrgan: '',
               sacmForThermalCutting: '',
               sacmForThermalSelfFusion: '',
               sacmForMolarTooth: '',
               sacmForSlitting: '',
             
      };
    },
    chooseprocessName(e, row, index) {
      const item = this.processOptions.find(v => v.processId === e)
      row['processCode'] = item.processCode
      row['processName'] = item.processName
      if (e && this.tableData[this.tableData.length - 1]['processId']) {
        this.tableData.push(JSON.parse(JSON.stringify(this.breakData)))
      }
    },
    chooseworkstationName(e, row, index) {
      const item = this.workstationList.find(v => v.workstationId === e)
      row['workstationName'] = item.workstationName
      row['workstationCode'] = item.workstationCode
    },
    /**重置组件状态 */
    resetState() {
      this.resetForm();
      this.tableData = [JSON.parse(JSON.stringify(this.breakData))];
    },
    // 查询工作中心信息
    handleWorkstationSelect() {
      this.$refs.WorkstationSelect.showFlag = true;
    },
    onWorkstationSelected(row) {
      if (row != undefined && row != null) {
        this.form.workstationId = row.workstationId;
        this.form.workstationName = row.workstationName;
        this.form.stdWorkingTime = row.stdWorkingTime;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.opt-btn{
  padding: 7px !important;
}
</style>
