<!--
 * @Descripttion: (质检管理/质检记录表/qa_inspect_record)
 * @version: (1.0)
 * @Author: (admin)
 * @Date: (2023-05-18)
 * @LastEditors: (admin)
 * @LastEditTime: (2023-05-18)
-->
<template>
  <div>
    <el-row :gutter="30" justify="space-evenly">
      <el-col :span="9">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" size="large"
          style="border:solid 1px var(--el-border-color);border-radius:4px;padding:20px;">
          <el-row>
            <el-form-item prop="deliverNo">
              <template #label>
                <el-text>交验单号</el-text>
              </template>
              <!-- <el-radio-group v-model="queryParamDeliverNo" @change="handleQuery">
                  <el-radio-button v-for="dict in sapDeliverNoCheck" :label="dict.deliverNo">
                    {{ dict.deliverNo }}
                  </el-radio-button>
                </el-radio-group> -->
              <el-select v-model="queryParams.deliverNo" placeholder="请选择" @change="handleQuery">
                <el-option v-for="dict in sapDeliverNoCheck" :key="dict.deliverNo" :label="dict.deliverNo"
                  :value="dict.deliverNo">
                </el-option>
              </el-select>
            </el-form-item>
            <el-button icon="finished" plain type="primary" style="margin-left:10px;"
              @click="submitDeliver">提交</el-button>
            <!-- <el-button icon="refresh" style="margin-left:10px;">重置</el-button> -->
            <el-form-item label="质检进度" prop="isComplate">
              <el-radio-group v-model="queryParams.isComplate" @change="handleQuery">
                <el-radio-button>全部</el-radio-button>
                <el-radio-button :label="true">未完成</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-row>
          <!-- <el-form-item label="质检结果" prop="checkResult">
            <el-radio-group v-model="queryParams.checkResult" @change="handleQuery">
              <el-radio-button :label=null>全部</el-radio-button>
              <el-radio-button v-for="dict in options.qaResultOptions" :label="dict.dictValue">
                  {{ dict.dictLabel }}
                </el-radio-button>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item prop="materialSpec">
            <template #label>
              <el-text>物料图号</el-text>
            </template>
            <el-input v-model="queryParams.materialSpec" ref="specInput" clearable placeholder="请选择输入物料图号"
              @keyup.enter="materialCurrentChange">
              <template #append>
                <el-button icon="search" @click="materialCurrentChange" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <template #label>
              <el-text>物料名</el-text>
            </template>
            <el-text>{{ form.materialName }}</el-text>
          </el-form-item>
          <el-form-item prop="bnSnCode">
            <template #label>
              <el-text>BN / SN码</el-text>
            </template>
            <el-input v-model="form.bnSnCode" ref="bnsnInput" placeholder="请输入BN / SN码" clearable />
          </el-form-item>
          <el-form-item prop="CheckOkQty">
            <template #label>
              <el-text>合格数量</el-text>
            </template>
            <el-input-number v-model="form.CheckOkQty" :min="0" :max="form.sumQty - form.sumCheckQty - form.CheckNgQty" />
          </el-form-item>
          <el-form-item prop="CheckNgQty">
            <template #label>
              <el-text type="danger">不合格数量</el-text>
            </template>
            <el-input-number v-model="form.CheckNgQty" :min="0" :max="form.sumQty - form.sumCheckQty"
              :change="NGQtyToOKQty()" />
          </el-form-item>
          <el-form-item>
            <el-button icon="check" type="primary" @click="submitForm">{{ $t('btn.submit') }}</el-button>
            <el-button icon="refresh" @click="reset(); handleQuery()">{{ $t('btn.reset') }}</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="15">
        <!-- 数据区域 -->
        <el-card shadow="never">
          <el-card style="
               height: 130px;
               width: 450px;
               margin: 5px;
               float: left;" shadow="hover" v-for="cell in dataList"
            @click="materialCurrentChange(null, cell.materialSpec)">
            <template #header>
              <el-text size="large">{{ cell.materialName }}</el-text>
              <el-text size="large" v-if="!cell.materialName.includes(cell.materialSpec)">{{ " " + cell.materialSpec
              }}</el-text>
              <el-text style="float:right;border:1px solid red;border-radius: 2px;padding:2px 4px;" type="danger"
                size="large" v-if="cell.sumQty == cell.sumCheckQty">完成</el-text>
            </template>
            <el-form :model="cell" label-width="80px" inline>
              <el-form-item label="交验单数量">{{ cell.sumQty }}</el-form-item>
              <el-form-item label="质检数量">{{ cell.sumCheckQty }}</el-form-item>
            </el-form>
          </el-card>
          <pagination class="mt10" style="clear:both;" background :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script setup name="qainspectrecord">
import {
  AddSapDeliverDtlInspectResult
} from '@/api/business/qainspectrecord.js'

import {
  GetSapDeliverRecordSumList, SubmitInspectResult
} from '@/api/business/sapdeliverrecord.js'

import { listSapDeliverNoCheck } from '@/api/business/sapdeliverrecord.js'
import { reactive } from 'vue';

const { proxy } = getCurrentInstance()

// 选中inspectId数组数组
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: '',
  sortType: 'asc',
})

const total = ref(0)
const dataList = ref([])
const sapDeliverNoCheck = ref([])
const queryRef = ref()

function getList() {
  loading.value = true
  GetSapDeliverRecordSumList(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
    // console.log(dataList.value)
  })
}
function getNoCheck() {
  const para = reactive({ deliverNo: '', bomNo: '', })
  listSapDeliverNoCheck(para).then(res => {
    const { code, data } = res
    if (code == 200) {
      sapDeliverNoCheck.value = data
      if (data.length > 0) {
        queryParams.deliverNo = sapDeliverNoCheck.value[0].deliverNo
        handleQuery()
      }
    }
  })
}
getNoCheck()
// 查询
function handleQuery() {
  queryParams.pageNum = 1
  // console.log(queryParams)
  getList()
  proxy.$refs['specInput'].focus()
}

/*************** form操作 ***************/
const formRef = ref()
const state = reactive({
  form: {},
  rules: {
    materialSpec: [{ required: true, message: "物料图号不能为空", trigger: "blur" }],
    bnSnCode: [{ required: true, message: "BN/SN码不能为空", trigger: "blur" }],
    CheckOkQty: [{ required: true, message: "合格数量不能为空", trigger: "blur", type: "number" }],
  },
  options: {
    keyFlagOptions: [], // 关键件标识字典
    operationResultOptions: [],// 操作结果字典
    materialTypeOptions: [],// 物料类型字典
    qaResultOptions: []//质检结果字典
  }
})

const { form, rules, options } = toRefs(state)
var dictParams = [
  { dictType: 'my_key_flag', columnName: 'keyFlagOptions' },
  { dictType: 'my_operation_result', columnName: 'operationResultOptions' },
  { dictType: 'my_material_type', columnName: 'materialTypeOptions' },
  { dictType: 'my_qa_result', columnName: 'qaResultOptions' },
]
proxy.getDicts(dictParams).then((response) => {
  response.data.forEach((element) => {
    state.options[element.columnName] = element.list
  })
})

// 选择物料
function materialCurrentChange(event, material) {
  if (material != null) {
    queryParams.materialSpec = material
  }
  else { console.log(material) }
  queryParams.pageNum = 1
  loading.value = true
  GetSapDeliverRecordSumList(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
      if (dataList.value.length == 1) {
        proxy.$refs['specInput'].focus()
        form.value = dataList.value[0]
        form.value.deliverNo = queryParams.deliverNo
        form.value.CheckNgQty = 0
        form.value.CheckOkQty = form.value.sumQty - form.value.sumCheckQty
        proxy.$refs['bnsnInput'].focus()
      }
      else {
        queryParams.materialSpec = ""
      }
    }
  })
}

// 重置表单
function reset() {
  form.value = {
    materialCode: undefined,
    materialName: undefined,
    materialSpec: undefined,
    sumQty: undefined,
    sumCheckQty: undefined,
  };
  queryParams.materialSpec = undefined
  proxy.resetForm("formRef")
}

// 不合格数量联动合格数量
function NGQtyToOKQty() {
  if (form.value.sumQty < (form.value.sumCheckQty + form.value.CheckOkQty + form.value.CheckNgQty)) {
    form.value.CheckOkQty = form.value.sumQty - form.value.sumCheckQty - form.value.CheckNgQty
  }
}
// 质检表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      // console.log(form.value)
      if (form.value.CheckOKQty == 0 && form.value.CheckNGQty == 0) {
        proxy.$modal.msgWarning("请至少输入合格数量或不合格数量！")
      }
      else {
        AddSapDeliverDtlInspectResult(form.value).then((res) => {
          reset()
          queryParams.materialSpec = undefined
          proxy.$modal.msgSuccess("质检成功！")
          getList()
        })
      }
      // if (form.value.inspectId != undefined && opertype.value === 2) {
      //   updateQaInspectRecord(form.value).then((res) => {
      //     proxy.$modal.msgSuccess("修改成功")
      //     open.value = false
      //     getList()
      //   })
      //     .catch(() => { })
      // } else {
      //   addQaInspectRecord(form.value).then((res) => {
      //     proxy.$modal.msgSuccess("新增成功")
      //     open.value = false
      //     getList()
      //   })
      //     .catch(() => { })
      // }
    }
  })
}
// 提交交验单
function submitDeliver() {
  console.log(queryParams.deliverNo)
  SubmitInspectResult(queryParams.deliverNo).then(res => {
    const { code, data } = res
    // console.log(code, data)
    if (code == 200) {
      if (data) {
        proxy.$modal.msgSuccess("提交成功！")
      }
      else {
        proxy.$modal.msgWarning("提交失败！请检查该交验单是否有未完成质检的物料。")
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.dialog-table-row {
  margin-bottom: 20px;
}

.dialog-table-row-head {
  float: right;
}
</style>
