<template>
  <el-dialog
    :title="!dataForm.id ? '新建' : '编辑'"
    :visible.sync="dialogVisible"
    width="1200px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="dataForm" :rules="dataRule" size="small" label-width="100px" label-position="right">
      <template v-if="!loading">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="工序" prop="procCd">
              <JnpfSelect v-model="dataForm.procCd" placeholder="请选择工序" :options="procOptions" :props="procProps" filterable clearable :disabled="!!dataForm.id" :style="{ width: '100%' }">
              </JnpfSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机台" prop="machineCd">
              <JnpfSelect v-model="dataForm.machineCd" placeholder="请选择机台" :options="machineOptions" :props="machineProps" filterable clearable :disabled="!!dataForm.id" :style="{ width: '100%' }">
              </JnpfSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="启用状态" prop="enabledStatus">
              <JnpfSelect v-model="dataForm.enabledStatus" placeholder="请选择状态" :options="enabledStatusOptions" :props="enabledStatusProps" clearable :style="{ width: '100%' }">
              </JnpfSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产品名称" prop="matCode">
              <JnpfSelect v-model="dataForm.matCode" placeholder="请选择物料" :options="materialOptions" filterable :props="materialProps" clearable @change="handleMaterialChange" :style="{ width: '100%' }">
              </JnpfSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格型号" prop="spec">
              <JnpfInput v-model="dataForm.spec" placeholder="请输入规格型号" clearable :style="{ width: '100%' }">
              </JnpfInput>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="备注" prop="remark">
              <JnpfTextarea v-model="dataForm.remark" placeholder="请输入备注" :style="{ width: '100%' }" :autoSize="{ minRows: 1, maxRows: 1 }" type="textarea">
              </JnpfTextarea>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div style="margin-bottom: 10px; display: flex; align-items: center;">
              <span style="font-weight: bold;">工艺参数信息</span>
              <el-button type="primary" size="small" @click="addParamItem" style="margin-left: 10px;">新 增</el-button>
            </div>
            <el-table :data="paramList" border style="width: 100%;" size="small">
              <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
              <el-table-column label="工艺参数名称(*)" prop="procParamName">
                <template slot-scope="scope">
                  <JnpfSelect v-model="scope.row.procParamName" placeholder="请选择" :options="paramNameOptions" :props="{ label: 'label', value: 'value' }" filterable clearable>
                  </JnpfSelect>
                </template>
              </el-table-column>
              <el-table-column label="标准值(*)" prop="standardValue">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.standardValue" placeholder="请输入"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="下限值(*)" prop="lowerLimit">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.lowerLimit" placeholder="请输入"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="上限值(*)" prop="upperLimit">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.upperLimit" placeholder="请输入"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="偏差" prop="dev">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.dev" placeholder="请输入"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="单位(*)" prop="procParamUnit">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.procParamUnit" placeholder="请输入"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="是否预警(*)" prop="isAlert">
                <template slot-scope="scope">
                  <JnpfSelect v-model="scope.row.isAlert" placeholder="请选择" :options="isAlertOptions" :props="{ label: 'label', value: 'value' }">
                  </JnpfSelect>
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="remark">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remark" placeholder="请输入"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="60" align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="removeParamItem(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">保 存</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { mapGetters } from 'vuex'
import { enabledStatusOptions } from '../common/dict'

export default {
  components: {},
  props: [],
  data() {
    return {
      dialogVisible: false,
      loading: false,
      btnLoading: false,
      formRef: 'formRef',
      eventType: '',
      dataForm: {
        id: '',
        procCd: undefined,
        procName: undefined,
        procId: undefined,
        matCode: undefined,
        matName: undefined,
        mateId: undefined,
        spec: undefined,
        machineCd: undefined,
        machineName: undefined,
        machineId: undefined,
        enabledStatus: '1',
        remark: undefined,
      },
      dataRule: {
        procCd: [
          {
            required: true,
            message: '请选择工序',
            trigger: 'change',
          },
        ],
        matCode: [
          {
            required: true,
            message: '请选择物料',
            trigger: 'change',
          },
        ],
        machineCd: [
          {
            required: true,
            message: '请选择机台',
            trigger: 'change',
          },
        ],
        enabledStatus: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'change',
          },
        ],
      },
      enabledStatusOptions,
      enabledStatusProps: { label: "fullName", value: "id" },
      procList: [],
      materialList: [],
      machineList: [],
      procOptions: [],
      materialOptions: [],
      machineOptions: [],
      procProps: { label: "label", value: "value" },
      materialProps: { label: "label", value: "value" },
      machineProps: { label: "label", value: "value" },
      paramList: [],
      paramNameOptions: [],
      isAlertOptions: [
        { label: '是', value: '0' },
        { label: '否', value: '1' },
      ],
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  created() {
    this.loadBaseData();
  },
  methods: {
    init(id) {
      this.dataForm.id = id || '';
      this.dialogVisible = true;
      this.loading = true;
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.resetFields();
        }

        if (this.dataForm.id) {
          request({
            url: `/api/example/machineparam/${this.dataForm.id}`,
            method: 'get'
          }).then(res => {
            this.dataForm = res.data;
            this.loading = false;
          }).catch(() => {
            this.loading = false;
          });
        } else {
          this.loading = false;
          this.resetFormData();
        }
      });
    },
    resetFormData() {
      this.dataForm = {
        id: '',
        procCd: undefined,
        procName: undefined,
        procId: undefined,
        matCode: undefined,
        matName: undefined,
        mateId: undefined,
        spec: undefined,
        machineCd: undefined,
        machineName: undefined,
        machineId: undefined,
        enabledStatus: '1',
        remark: undefined,
      };
    },
    loadBaseData() {
      this.loadProcList();
      this.loadMaterialList();
      this.loadMachineList();
      this.loadParamNameOptions();
    },
    loadParamNameOptions() {
      request({
        url: `/api/example/procparam/getSelect`,
        method: 'get'
      }).then(res => {
        const list = res.data || [];
        this.paramNameOptions = list.map(item => ({
          label: item.name || '',
          value: item.id || '',
        }));
      });
    },
    addParamItem() {
      this.paramList.push({
        procParamName: undefined,
        standardValue: undefined,
        lowerLimit: undefined,
        upperLimit: undefined,
        dev: undefined,
        procParamUnit: undefined,
        isAlert: '0',
        remark: undefined,
      });
    },
    removeParamItem(index) {
      this.paramList.splice(index, 1);
    },
    loadProcList() {
      request({
        url: `/api/example/proc/getProcList`,
        method: 'get'
      }).then(res => {
        this.procList = res.data || [];
        this.procOptions = this.procList.map(item => ({
          label: item.procName,
          value: item.procCd,
          procName: item.procName,
          id: item.id
        }));
      });
    },
    loadMaterialList() {
      request({
        url: `/api/example/material/getMaterialList`,
        method: 'get',
        params: { keyWord: '' }
      }).then(res => {
        this.materialList = res.data || [];
        this.materialOptions = this.materialList.map(item => ({
          label: `${item.matName}`,
          value: item.id,
          matName: item.name,
          id: item.id,
          spec: item.spec
        }));
      });
    },
    loadMachineList() {
      request({
        url: `/api/example/machine/getMachineList`,
        method: 'get',
        params: { keyWord: '' }
      }).then(res => {
        this.machineList = res.data || [];
        this.machineOptions = this.machineList.map(item => ({
          label: `${item.name}`,
          value: item.id,
          machineName: item.name,
          id: item.id
        }));
      });
    },
    handleMaterialChange(value) {
      if (value) {
        const material = this.materialOptions.find(item => item.value === value);
        if (material) {
          this.dataForm.spec = material.spec || '';
        }
      } else {
        this.dataForm.spec = '';
      }
    },
    dataFormSubmit() {
      // 验证表格必填字段
      for (let i = 0; i < this.paramList.length; i++) {
        const item = this.paramList[i];
        if (!item.procParamName) {
          this.$message.error(`第 ${i + 1} 行工艺参数名称不能为空`);
          return;
        }
        if (!item.standardValue) {
          this.$message.error(`第 ${i + 1} 行标准值不能为空`);
          return;
        }
        if (!item.lowerLimit) {
          this.$message.error(`第 ${i + 1} 行下限值不能为空`);
          return;
        }
        if (!item.upperLimit) {
          this.$message.error(`第 ${i + 1} 行上限值不能为空`);
          return;
        }
        if (!item.procParamUnit) {
          this.$message.error(`第 ${i + 1} 行单位不能为空`);
          return;
        }
        if (!item.isAlert) {
          this.$message.error(`第 ${i + 1} 行是否预警不能为空`);
          return;
        }
      }
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          const isEdit = !!this.dataForm.id;
          const url = isEdit ? `/api/example/machineparam/${this.dataForm.id}` : '/api/example/machineparam';
          const method = isEdit ? 'put' : 'post';

          const proc = this.procOptions.find(item => item.value === this.dataForm.procCd);
          const material = this.materialOptions.find(item => item.value === this.dataForm.matCode);
          const machine = this.machineOptions.find(item => item.value === this.dataForm.machineCd);

          const submitData = {
            ...this.dataForm,
            procName: proc ? proc.procName : undefined,
            procId: proc ? proc.id : undefined,
            matName: material ? material.matName : undefined,
            mateId: material ? material.id : undefined,
            machineName: machine ? machine.machineName : undefined,
            machineId: machine ? machine.id : undefined,
            detailList: this.paramList,
          };

          request({
            url: url,
            method: method,
            data: submitData
          }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.btnLoading = false;
                this.dialogVisible = false;
                this.$emit('refresh', true)
              }
            })
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    handleClose() {
      this.dialogVisible = false;
      this.$emit('refresh', true)
    },
  }
}
</script>
