<template>
  <el-dialog
    v-dialogDrag
    :title="inspectTitle"
    :visible.sync="visible"
    append-to-body
    width="1200px"
    @open="dialogOpen"
    @close="dialogClose"
  >
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      v-if="queryObj"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="98px"
      :rules="rules"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="方案名称" prop="name">
            <InspectionType
              v-model="queryObj.name"
              :type="queryParams.type"
              :audit-status="auditStatus"
              filterable
              placeholder="请选择检验方案"
              :disabled="inspectDisable"
              @change="inspectNameChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-button
            v-hasPermi="['wms:material-item:query']"
            type="primary"
            icon="
            el-icon-edit"
            disabled
            @click="handleEditCase"
          >修改方案</el-button>
          <el-button
            v-hasPermi="['wms:material-item:query']"
            type="primary"
            icon="el-icon-refresh"
            :disabled="refreshDisable"
            @click="handleRefresh"
          >刷新</el-button>
          <el-button
            v-show="copyShow"
            type="primary"
            icon="el-icon-plus"
            @click="handleCopy"
          >新增标准</el-button>
        </el-col>

      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="物料编码" prop="materialNo">
            <MaterialSelect
              ref="materialOrder"
              v-model="queryParams.materialNo"
              clearable
              :disabled="selectDisable"
              @change="materialChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检验标准版本" prop="version">
            <el-input
              v-model="queryObj.version"
              placeholder="请输入检验标准版本"
              disabled
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入物料名称"
              clearable
              disabled
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <!-- 列表 -->
    <el-table
      :data="list"
      border
      size="mini"
    >
      <el-table-column label="检验项编码" align="center" prop="inspectionNo">
        <template slot-scope="scope">
          <InspectCaseSelect
            ref="inspectCaseSelect"
            v-model="scope.row.inspectionNo"
            filterable
            :list="list"
            :type="queryParams.type"
            placeholder="请选择检验项名称"
            :disabled="scope.row.isEditCase !== 0"
            @change="inspectCaseChange"
          />
        </template>
      </el-table-column>
      <el-table-column label="检验项名称" align="center" prop="inspectionName" />
      <el-table-column label="检验项类型" align="center" prop="inspectionModel">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.WMS_INSPECTION_TYPE" :value="scope.row.inspectionModel" />
        </template>
      </el-table-column>
      <el-table-column
        label="检查规格/标准"
        align="center"
        prop="standardPre"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.inspectionModel === 1"
            v-model="scope.row.standardPre"
            :disabled="saveDisable"
            placeholder="请输入检查标准"
          />
          <span v-else>{{ scope.row.standardPre }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检查工具" align="center" prop="tool">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.WMS_INSPECTION_TOOLS" :value="scope.row.tool" />
        </template>
      </el-table-column>
      <el-table-column label="检查数量" align="center" prop="checkQuantity">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.WMS_CHECK_QUANTITY" :value="scope.row.checkQuantity" />
        </template>
      </el-table-column>
      <el-table-column label="下限值" align="center" prop="minValue">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.minValue"
            oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
            :disabled="scope.row.inspectionModel === 1 || saveDisable"
            @change="minValueChange(scope.row, scope.row.minValue)"
          />
        </template>
      </el-table-column>
      <el-table-column label="标准值" align="center" prop="standValue">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.standValue"
            oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
            :disabled="scope.row.inspectionModel === 1 || saveDisable"
            @change="standValueChange(scope.row, scope.row.standValue)"
          />
        </template>
      </el-table-column>
      <el-table-column label="上限值" align="center" prop="maxValue">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.maxValue"
            oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
            :disabled="scope.row.inspectionModel === 1 || saveDisable"
            @change="maxValueChange(scope.row, scope.row.maxValue)"
          />
        </template>
      </el-table-column>
    </el-table>

    <span slot="footer">
      <el-button
        type="primary"
        :loading="addLoading"
        :disabled="saveDisable"
        @click="handleSave"
      >{{ btnText === 'save'?'保存':'新增' }}</el-button>
      <el-button
        type="primary"
        :disabled="commitDisable"
        :loading="submitLoading"
        @click="handleSubmit"
      >提交</el-button>
    </span>
    <!-- 修改方案 -->
    <!-- <HandleCase ref="handleCase" :caselist="list" @caseComplete="caseComplete" /> -->
  </el-dialog>
</template>

<script>
import { getUpdateMaterialItemDetailPage, updateBatchInspection, pushToVerifyInspection, getMaterialAdditionPageNew } from '@/api/wms/quality/iqcInspectionExecute'
import { createNewInspection } from '@/api/wms/quality/inspectStandardApproval'
// import HandleCase from '../../components/HandleCase.vue'
import InspectionType from './InspectionType.vue'
import MaterialSelect from '../inspectStandardApproval/MaterialSelect.vue'
import InspectCaseSelect from '../../components/InspectCaseSelect.vue'

export default {
  name: 'UpdateInspection',
  components: {
    // HandleCase,
    InspectionType,
    MaterialSelect,
    InspectCaseSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      submitLoading: false,
      addLoading: false,

      inspectDisable: false,
      inspectTitle: '修改检验标准',
      // 是否需要检验
      refreshDisable: false,
      // 显示搜索条件
      showSearch: true,
      copyShow: false,
      // 总条数
      total: 0,
      // 物料检验方案明细列表
      list: [],
      // 弹出层标题
      title: '',
      // 保存提交按钮名称
      btnText: 'save',
      // 是否显示弹出层
      visible: false,
      queryObj: {
        version: undefined,
        name: null
      },
      // 刷新的参数id
      wmsMaterialAdditionalId: '',
      // 审批状态
      auditStatus: null,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        wmsMaterialAdditionalId: undefined,
        materialNo: undefined,
        processNo: undefined,
        type: null
      },
      // 保存提交置灰
      saveDisable: false,
      commitDisable: false,
      selectDisable: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {

      }
    }
  },
  methods: {

    /** 查询列表 */
    getList() {
      this.loading = true
      // wmsMaterialAdditionalId不为空或新增时调用接口getMaterialAdditionPageNew
      if (this.queryParams.wmsMaterialAdditionalId === undefined || this.btnText === 'add') {
        const params = {
          pageNo: 1,
          pageSize: 10,
          wmsMaterialItemMasterId: this.queryParams.wmsMaterialItemMasterId,
          processNo: this.queryParams.processNo,
          code: this.queryParams.materialNo,
          type: this.queryParams.type
        }
        getMaterialAdditionPageNew(params).then(res => {
          this.list = res.data.list
          this.total = res.data.total
        }).finally(() => {
          this.loading = false
        })
      } else {
        const params = {
          pageNo: 1,
          pageSize: 10,
          wmsMaterialAdditionalId: this.queryParams.wmsMaterialAdditionalId,
          name: null,
          processNo: this.queryParams.processNo,
          type: this.queryParams.type
        }
        // 执行查询
        getUpdateMaterialItemDetailPage(params).then(response => {
          this.list = response.data.list
          this.total = response.data.total
        }).finally(() => {
          this.loading = false
        })
      }
    },

    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        wmsMaterialAdditionalId: undefined,
        wmsMaterialItemMasterId: undefined,
        wmsInspectionItemId: undefined,
        code: undefined,
        minValue: undefined,
        standValue: undefined,
        maxValue: undefined,
        standardPre: undefined,
        tool: undefined,
        checkQuantity: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 保存/新增
    handleSave() {
      this.list = this.list.map(item => {
        item.code = this.queryParams.code === undefined ? this.queryParams.materialNo : this.queryParams.code
        item.inspectionItemId = item.inspectionItemId === undefined ? item.wmsInspectionItemId : item.inspectionItemId
        const {
          code,
          inspectionItemId: wmsInspectionItemId,
          inspectionModel,
          inspectionName,
          inspectionNo,
          maxValue,
          minValue,
          standValue,
          standardPre,
          tool,
          checkQuantity,
          wmsMaterialItemMasterId,
          wmsMaterialAdditionalId
        } = item
        return {
          code,
          wmsInspectionItemId,
          inspectionModel,
          inspectionName,
          inspectionNo,
          maxValue,
          minValue,
          standValue,
          standardPre,
          tool,
          checkQuantity,
          wmsMaterialItemMasterId,
          wmsMaterialAdditionalId
        }
      })
      if (this.btnText === 'save') {
        this.addLoading = true
        const params = {
          processNo: this.queryParams.processNo,
          wmsMaterialAdditionalId: this.queryParams.wmsMaterialAdditionalId,
          code: this.queryParams.code === undefined ? this.queryParams.materialNo : this.queryParams.code,
          updateNewReqVOList: this.list,
          type: this.queryParams.type
        }
        updateBatchInspection(params).then(res => {
          if (res.data === true) {
            this.$modal.msgSuccess('保存成功!')
            this.$emit('saveComplete')
            this.addLoading = false
          }
        }).finally(() => {
          this.addLoading = false
        })
      } else {
        this.addLoading = true
        const params = {
          processNo: this.queryParams.processNo,
          code: this.queryParams.code === undefined ? this.queryParams.materialNo : this.queryParams.code,
          createDetailReqVOList: this.list,
          type: this.queryParams.type
        }
        createNewInspection(params).then(res => {
          this.visible = false
          this.queryParams.wmsMaterialAdditionalId = res.data
          this.$modal.msgSuccess('新增成功!')
          this.$emit('addComplete')
          this.handleSubmit()
          this.addLoading = false
        }).finally(() => {
          this.addLoading = false
        })
      }
    },
    // 提交
    handleSubmit() {
      this.submitLoading = true
      // 处理list参数
      const params = {
        processNo: this.queryParams.processNo,
        code: this.queryParams.code === undefined ? this.queryParams.materialNo : this.queryParams.code,
        wmsMaterialAdditionalId: this.queryParams.wmsMaterialAdditionalId,
        updateNewReqVOList: this.list,
        type: this.queryParams.type
      }
      pushToVerifyInspection(params).then(res => {
        if (res.data === true) {
          this.$emit('addComplete')
          this.$modal.msgSuccess('提交成功')
          this.visible = false
          this.submitLoading = false
        }
      }).finally(() => {
        this.submitLoading = false
      })
    },
    dialogOpen() {
      if (this.btnText === 'add') {
        this.inspectTitle = '新增检验标准'
        this.getList()
      }
      if (this.btnText === 'save') {
        this.getList()
      }
    },
    // 修改方案 --- iqc 暂时禁用不可修改
    handleEditCase() {
      const { code, name, id } = this.queryObj
      this.$router.push({ path: '/quality/inspect-case-operate', query: { caseInspectionType: '0', type: 0, auditStatus: null, code, name, id }})
      // this.$refs.handleCase.queryParams.id = id
      // this.$refs.handleCase.queryParams.code = code
      // this.$refs.handleCase.queryParams.type = 0
      // this.$refs.handleCase.queryParams.inspectionNo = code
      // this.$refs.handleCase.queryParams.inspectionName = name
      // this.$refs.handleCase.code = code
      // this.$refs.handleCase.caseTitle = name
      // this.$refs.handleCase.viewOpen = true
      // this.$refs.handleCase.caseParams = this.queryObj
      // this.$refs.handleCase.queryParams.wmsMaterialAdditionalId = this.queryParams.wmsMaterialAdditionalId
      // this.$refs.handleCase.materialNo = this.queryParams.materialNo
      // this.$refs.handleCase.title = '修改'
      // this.$refs.handleCase.inspectDisable = true
      // this.$refs.handleCase.inspectNoDisable = true
      // this.$refs.handleCase.queryParams.caseInspectionType = '0'
    },
    // 标准值校验
    standValueChange(row, v) {
      const { maxValue, minValue } = row
      v = parseInt(v, 10)
      if ((maxValue !== null && parseInt(maxValue, 10) < v) || (minValue !== null && parseInt(minValue, 10) > v)) {
        this.$modal.notifyWarning('标准值不能大于上限值，不能小于下限值，请重新输入标准值!')
      }
    },
    // 最小值校验
    minValueChange(row, v) {
      const { standValue } = row
      if (standValue !== null && parseInt(v, 10) > parseInt(standValue, 10)) {
        this.$modal.notifyWarning('下限值不能大于标准值，请重新填入!')
      }
    },
    // 最大值校验
    maxValueChange(row, v) {
      const { standValue } = row
      if (standValue !== null && parseInt(standValue, 10) > parseInt(v, 10)) {
        this.$modal.notifyWarning('上限值不能小于标准值，请重新填入!')
      }
    },
    // 更新刷新数据
    caseComplete() {
      this.getList()
      this.$emit('updateCase')
    },
    // 选择检验方案
    inspectNameChange(v) {
      const query = this.queryParams
      const { id } = v
      query.wmsMaterialItemMasterId = id
      this.handleRefresh()
    },
    // 选择物料 -- iqc
    materialChange(v) {
      const { materialNo, materialName } = v
      this.queryParams.code = materialNo
      this.queryParams.name = materialName
      this.getList()
    },
    // 已审核复制标准
    handleCopy(row) {
      this.btnText = 'add'
      this.inspectTitle = '新增检验标准'
      this.queryObj.version = '草稿'
      // 检验方案可选
      this.inspectDisable = false
      this.getList()
      this.saveDisable = false
      this.selectDisable = true
    },
    // 弹出层关闭
    dialogClose() {
      if (this.queryObj) {
        this.queryObj.name = undefined
      }
      this.queryParams = {}
      this.list = []
    },
    // 刷新--> 获取最新方案
    handleRefresh() {
      const params = {
        code: this.queryParams.materialNo,
        wmsMaterialItemMasterId: this.queryParams.wmsMaterialItemMasterId === undefined ? this.queryObj.id : this.queryParams.wmsMaterialItemMasterId,
        wmsMaterialAdditionalId: this.wmsMaterialAdditionalId,
        processNo: this.queryParams.processNo,
        type: this.queryParams.type
      }
      getMaterialAdditionPageNew(params).then(res => {
        this.list = res.data.list
        this.total = res.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    // 选择检验项
    inspectCaseChange(v) {
      const { inspectionNo, inspectionName, inspectionModel, inspectionType, inspectionItemId, tool, checkQuantity } = v
      const filterObj = this.list.find(item => item.inspectionNo === inspectionNo)
      filterObj.inspectionModel = inspectionModel
      filterObj.inspectionName = inspectionName
      filterObj.inspectionType = inspectionType
      filterObj.inspectionItemId = inspectionItemId
      filterObj.tool = tool
      filterObj.checkQuantity = checkQuantity
      filterObj.isEditCase = 1
    }
  }
}
</script>
