
<!-- 检验策略弹窗 -->
<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px" >
    <div class="p-20px m--10px" style="max-height: 80vh; overflow-y: auto">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        label-position="left"
      >
        <!-- 规则 -->
        <div class="item">
          <div class="title">规则</div>
          <el-row key="规则row">
            <el-col :span="24" key="代码col">
              <el-form-item key="代码formItem" label="代码" prop="strategyCode">
                <el-input key="代码input"
                  v-model="formData.strategyCode"
                  placeholder="请输入代码"
                  clearable
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="24" key="名称col">
              <el-form-item key="名称formItem" label="名称" prop="name">
                <el-input key="名称input" v-model="formData.name" placeholder="请输入名称" clearable :disabled="formData.name=='默认规则'&&formType=='update'"/>
              </el-form-item>
            </el-col>
            <el-col :span="24" key="描述col">
              <el-form-item key="描述formItem" label="描述" prop="description">
                <el-input key="描述input" v-model="formData.description" placeholder="请输入描述" clearable :disabled="formData.name=='默认规则'&&formType=='update'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" key="优先级col">
              <el-form-item key="优先级formItem" label="优先级" prop="priority">
                <el-input-number key="优先级input" v-model="formData.priority" :min="0" :disabled="formData.name=='默认规则'&&formType=='update'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" key="状态col">
              <el-form-item key="状态formItem" label="状态" prop="status">
                <el-switch key="状态switch" v-model="formData.status" :disabled="formData.name=='默认规则'&&formType=='update'"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 规则条件 -->
        <div class="item mt-20px">
          <div class="title">规则条件</div>
          <el-row key="规则条件row">
            <el-col :span="24" v-for="(item, index) in formData.condition" :key="'规则条件col'+index">
              <!-- 供应商类型 -->
              <el-form-item :key="'供应商类型formItem'+index" v-if="index == 0" label="供应商类型" class="flex-top err-120">
                <el-select :key="'供应商类型select'+index"
                  v-model="item.Operator"
                  placeholder="请选择范围"
                  style="width: 110px; margin-right: 10px"
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                >
                  <el-option
                    :label="cur.label"
                    :value="cur.value"
                    v-for="cur in options.supplierTypeRangeOptions"
                    :key="'供应商类型option'+cur.value"
                  />
                </el-select>
                <el-select :key="'供应商类型Value'+index"
                  v-model="item.Value"
                  placeholder="请选择供应商类型"
                  style="flex: 1"
                  clearable
                  @change="changeSupplierType"
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                >
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.SUPPLIER_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="'供应商类型Value'+dict.value"
                  />
                </el-select>
              </el-form-item>
              <!-- 供应商 -->
              <el-form-item :key="'供应商formItem'+index"
                v-else-if="index == 1"
                label="供应商"
                class="err-120"
                :prop="'condition.' + index + '.Value'"
                :rules="{
                  required: false,
                  message: '请选择供应商',
                  trigger: 'change'
                }"
              >
                <el-select :key="'供应商Operator'+index"
                  v-model="item.Operator"
                  placeholder="请选择范围"
                  style="width: 110px; margin-right: 10px"
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                >
                  <el-option
                    :label="cur.label"
                    :value="cur.value"
                    v-for="cur in options.supplierRangeOptions"
                    :key="'供应商option'+cur.value"
                  />
                </el-select>
                <el-select :key="'供应商Value'+index"
                  v-model="item.Value"
                  placeholder="请选择供应商"
                  style="flex: 1"
                  clearable
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                >
                  <el-option
                    v-for="cur in options.supplierList"
                    :key="'供应商Valueoption'+cur.code"
                    :label="cur.name"
                    :value="cur.code"
                  />
                </el-select>
              </el-form-item>
              <!-- 物料 -->
              <el-form-item :key="'物料formItem'+index" v-else-if="index == 2" label="物料" class="flex-top err-120">
                <el-select :key="'供应商Operator'+index"
                  v-model="item.Operator"
                  placeholder="请选择范围"
                  style="width: 110px; margin-right: 10px"
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                >
                  <el-option
                    :label="cur.label"
                    :value="cur.value"
                    v-for="cur in options.ItemCodeRangeOptions"
                    :key="'供应商OperatorOption'+cur.value"
                  />
                </el-select>
                <el-input :key="'供应商Value'+index"
                  v-model="item.Value"
                  placeholder="请输入物料，多个物料以逗号分隔"
                  clearable
                  style="flex: 1"
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 规则配置 -->
        <div class="item mt-20px">
          <div class="title">规则配置</div>
          <el-row key="规则配置row">
            <!-- 开始时间 -->
            <el-col :span="24" key="开始时间col">
              <!-- 检验方式 -->
              <el-form-item label="检验方式" class="flex-top" key="检验方式formItem">
                <div class="checkbox">
                  <el-radio-group key="检验方式radioGroup"
                    v-model="formData.configuration.InspectType"
                    @change="changeInspectType"
                  >
                    <el-radio
                      :label="cur.value"
                      v-for="cur in getStrDictOptions(DICT_TYPE.INSPECT_TYPE)"
                      :key="'检验方式radio'+cur.value"
                      >{{ cur.label }}</el-radio
                    >
                  </el-radio-group>
                </div>
              </el-form-item>
            </el-col>
            <!-- 抽检方式 -->
            <el-col :span="24" v-if="formData.configuration.InspectType == 'SAMPLING'" key="抽检方式col">
              <el-form-item label="抽检方式" class="flex-top" key="抽检方式formItem">
                <div class="checkbox">
                  <el-radio-group v-model="formData.configuration.SampleMethod" key="抽检方式radioGroup">
                    <el-radio
                      :label="cur.value"
                      v-for="cur in getStrDictOptions(DICT_TYPE.SAMPLE_METHOD)"
                      @change="changeSampleMethod"
                      :key="'抽检方式radio'+cur.value"
                      >{{ cur.label }}</el-radio
                    >
                  </el-radio-group>
                </div>
              </el-form-item>
            </el-col>
            <!-- 抽检规则 -->
            <el-col :span="24" v-if="formData.configuration.InspectType == 'SAMPLING'" key="抽检规则col">
              <el-form-item label="抽检规则" class="flex-top" prop="configurationRules" key="抽检规则formItem">
                <div
                  style="flex: 1; display: flex; align-items: center; margin-bottom: 10px"
                  v-for="(cur, key) in formData.configuration.AqlList"
                  :key="'抽检规则div'+key"
                >
                  <div :key="'抽检规则div1'+key" style="width: 26px; display: flex">
                    <Icon :key="'抽检规则icon'+key"
                      icon="ep:remove"
                      color="#757575"
                      size="26"
                      style="cursor: pointer"
                      @click="handleDeleteTable(formData.configuration.AqlList, cur, key)"
                      v-if="formData.configuration.AqlList?.length > 1"
                    />
                  </div>
                  <el-input-number :key="'抽检规则input1'+key"
                    v-model="cur.FloorQty"
                    :min="1"
                    :max="cur.CeilingQty - 1"
                    class="ml-20px mr-20px"
                    style="width: 100px"
                    controls-position="right"
                    @blur="inputNumberBlur"
                  />
                  <div>至</div>
                  <el-input-number :key="'抽检规则input2'+key"
                    v-model="cur.CeilingQty"
                    :min="cur.FloorQty + 1"
                    class="ml-20px mr-20px"
                    style="width: 100px"
                    controls-position="right"
                    @blur="inputNumberBlur"
                  />
                  <div>抽样数</div>
                  <el-input-number :key="'抽检规则input3'+key"
                    v-model="cur.SampleValue"
                    :min="1"
                    :max="formData.configuration.SampleMethod == 'QTY' ? Infinity : 100"
                    class="ml-20px mr-20px"
                    style="width: 100px"
                    controls-position="right"
                    @blur="inputNumberBlur"
                  />
                  <div :key="'抽检规则div2'+key">{{ formData.configuration.SampleMethod == 'QTY' ? 'EA' : '%' }}</div>
                </div>
                <div class="button flex">
                  <div @click="handleAddTable(formData.configuration.AqlList)">
                    <Icon icon="ep:circle-plus" color="#409eff" size="26" style="cursor: pointer" />
                    <div>添加条件</div>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <template #footer>
      <!-- 按钮-->
      <TableHead :HeadButttondata="Butttondata" @buttonBaseClick="buttonBaseClick" />
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as defaultButtons from '@/utils/disposition/defaultButtons'
defineOptions({ name: 'SupplieDeliveryStrategyAddForm' })
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { getSupplierList } from '@/api/wms/supplier'
import * as RuleApi from '@/api/wms/rule'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref() // 表单 Ref

const formStrategyCode = ref('')
// form表单数据
const formData = ref({
  id: '',
  strategyCode: formStrategyCode.value, //策略代码id
  name: '', //名称
  description: '', //描述
  priority: '', //优先级
  status: true, //状态
  //规则条件集合
  condition: [
    // 供应商类型
    { ParamCode: 'SupplierType', Operator: '==', Value: '' },
    // 供应商
    { ParamCode: 'SupplierCode', Operator: '==', Value: '' },
    // 物料代码
    { ParamCode: 'ItemCode', Operator: 'IN', Value: [] }
  ],
  configuration: {
    // 检验方式
    InspectType: 'EXEMPT',
    // 抽检方式
    SampleMethod: 'QTY',
    // 抽检规则列表
    AqlList: [
      {
        FloorQty: 1,
        CeilingQty: 2,
        SampleValue: 1
      }
    ]
  },
  configurationRules: '1' //规则配置验证
})

// 验证规则
const rules = ref({
  strategyCode: [
    { required: true, message: '请输入代码', trigger: 'blur' },
    { max: 50, message: '不得超过50个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入名字', trigger: 'blur' },
    { max: 50, message: '不得超过50个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' },
    { max: 50, message: '不得超过50个字符', trigger: 'blur' }
  ],
  priority: [{ required: true, message: '请输入优先级', trigger: 'blur' }],
  configurationRules: [{ required: true, message: '抽奖规则请填写完全', trigger: 'blur' }]
})

// 所有的范围类型
const rangeOptions = [
  { value: '==', label: '等于' },
  { value: '!=', label: '不等于' },
  { value: '>', label: '大于' },
  { value: '<', label: '小于' },
  { value: '>=', label: '大于等于' },
  { value: '<=', label: '小于等于' },
  { value: 'IN', label: '包含' },
  { value: 'NOT IN', label: '不包含' },
  { value: 'NULL', label: '为空' },
  { value: 'NOT NULL', label: '不为空' }
]
const formatRangeOptions = (...rest) => {
  // 交集
  let result = rangeOptions.filter((aItem) => rest.some((bItem) => aItem.value === bItem))
  return result
}
// 下拉框列表集合
const options = reactive({
  // 供应商类型范围下拉框列表
  supplierTypeRangeOptions: formatRangeOptions('=='),
  // 供应商列表
  supplierTypeOptions: [],
  // 供应商范围下拉框列表
  supplierRangeOptions: formatRangeOptions('=='),
  //供应商列表
  supplierList: [],
  // 物料范围下拉框列表
  ItemCodeRangeOptions: formatRangeOptions('IN', 'NOT IN')
})
// 获取供应商列表的参数
const querySupplierParams = ref({
  type: ''
})
// 弹窗按钮
const Butttondata = ref([
  defaultButtons.formSaveBtn(null), // 保存
  defaultButtons.formCloseBtn(null) // 关闭
])
// 按钮事件
const buttonBaseClick = (val, item) => {
  // 保存
  if (val == 'save') {
    submitForm()
  }
  // 关闭
  else if (val == 'close') {
    dialogVisible.value = false
  }
}

// 获取供应商列表
const getFormSupplierList = async () => {
  options.supplierList = await getSupplierList(querySupplierParams.value)
}

// 选择供应商类型
const changeSupplierType = (e) => {
  querySupplierParams.value.type = e
  formData.value.condition[1].Value = []
  getFormSupplierList()
}
getFormSupplierList()
// 改变检验方式的时候
function changeInspectType(e) {
  if (e == 'SAMPLING') {
    formData.value.configuration.SampleMethod = 'QTY'
    formData.value.configuration.AqlList = [
      {
        FloorQty: 1,
        CeilingQty: 2,
        SampleValue: 1
      }
    ]
  }
}
// 改变抽检方式的时候
function changeSampleMethod(e) {
  if (e == 'PERCENT') {
    formData.value.configuration.AqlList.forEach((cur) => {
      if (cur.SampleValue > 100) {
        cur.SampleValue = 100
      }
    })
  }
}
/** 打开弹窗 */
const open = async (type: string, strategyCode: string, id?: number) => {
  formStrategyCode.value = strategyCode
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      let data = await RuleApi.getRule(id)
      formData.value.id = data.id
      formData.value.strategyCode = data.strategyCode
      formData.value.name = data.name
      formData.value.description = data.description
      formData.value.priority = data.priority
      formData.value.status = data.status == 0 ? true : false
      // if (formData.value.priority == 0) {
      //   Butttondata.value = [
      //     defaultButtons.formSaveBtn({ disabled: true }), // 保存
      //     defaultButtons.formCloseBtn(null) // 关闭
      //   ]
      // } else {
        Butttondata.value = [
          defaultButtons.formSaveBtn(null), // 保存
          defaultButtons.formCloseBtn(null) // 关闭
        ]
      // }
      if (data.condition) {
        formData.value.condition = JSON.parse(data.condition)
      }
      if (data.configuration) {
        formData.value.configuration = JSON.parse(data.configuration)
      }

      querySupplierParams.value.type = formData.value?.condition[0]?.Value || ''
      getFormSupplierList()
    } finally {
      formLoading.value = false
    }
  } else {
    Butttondata.value = [
      defaultButtons.formSaveBtn(null), // 保存
      defaultButtons.formCloseBtn(null) // 关闭
    ]
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const hasSameData = (array) => {
  for (let k = 0; k < array.length; k++) {
    for (let n = k + 1; n < array.length; n++) {
      if(array[k].FloorQty <= array[n].FloorQty && array[n].FloorQty<=array[k].CeilingQty){
        return true
      }
    }
  }
  return false
}
const submitForm = async () => {
  // 校验表单
  inputNumberBlur()
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // if (formData.value.priority == 0) {
  //   message.error('优先级不可以为0')
  //   return
  // }
  if (hasSameData(formData.value.configuration.AqlList)) {
    message.error('抽检规则数据范围重叠，请重新填写')
    return
  }
  // 提交请求
  formLoading.value = true
  if (formData.value.configuration.InspectType != 'SAMPLING') {
    formData.value.configuration.SampleMethod = ''
    formData.value.configuration.AqlList = []
  }
  try {
    let data = {
      id: formData.value.id,
      strategyCode: formData.value.strategyCode, //策略代码
      name: formData.value.name, //名称
      description: formData.value.description, //描述
      priority: formData.value.priority, //优先级
      status: formData.value.status ? 0 : 1, //状态
      //规则条件集合
      condition: JSON.stringify(formData.value.condition),
      configuration: JSON.stringify(formData.value.configuration)
    }
    if (formType.value === 'create') {
      await RuleApi.createRule(data)
      message.success(t('common.createSuccess'))
    } else {
      await RuleApi.updateRule(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: '',
    strategyCode: formStrategyCode.value, //策略代码
    name: '', //名称
    description: '', //描述
    priority: '', //优先级
    status: true, //状态
    //规则条件集合
    condition: [
      // 供应商类型
      { ParamCode: 'SupplierType', Operator: '==', Value: '' },
      // 供应商
      { ParamCode: 'SupplierCode', Operator: '==', Value: '' },
      // 物料代码
      { ParamCode: 'ItemCode', Operator: 'IN', Value: [] }
    ],
    configuration: {
      // 检验方式
      InspectType: 'EXEMPT',
      // 抽检方式
      SampleMethod: 'QTY',
      // 抽检规则列表
      AqlList: [
        {
          FloorQty: 1,
          CeilingQty: 2,
          SampleValue: 1
        }
      ]
    },
    configurationRules: '1' //规则配置验证
  }
}

// 添加抽查规则
const handleAddTable = (item) => {
  item.push({
    FloorQty: 1,
    CeilingQty: 2,
    SampleValue: 1
  })
}
// 删除抽查规则
const handleDeleteTable = (item, cur, key) => {
  item.splice(key, 1)
}
//失去焦点的时候验证
const inputNumberBlur = () => {
  let arr = []
  formData.value.configuration.AqlList.forEach((item) => {
    let bol = false
    if (!item.FloorQty || !item.CeilingQty || !item.SampleValue) {
      bol = false
    } else {
      bol = true
    }
    arr.push(bol)
  })
  const isEmpty = arr.some((cur) => {
    return !cur
  })
  if (isEmpty) {
    formData.value.configurationRules = ''
    return
  } else {
    formData.value.configurationRules = '1'
  }
}
</script>
<style scoped lang="scss">
.item {
  border: 1px solid #dedede;
  border-radius: 4px;
  padding: 30px 30px 5px;
  position: relative;

  .title {
    position: absolute;
    background: white;
    padding: 0px 10px;
    position: absolute;
    top: 0px;
    height: 30px;
    line-height: 30px;
    margin-top: -15px;
  }
}

.checkbox {
  background: #f5f5f5;
  flex: 1;
  padding: 0px 15px;
  border-radius: 2px;
}

::v-deep .flex-top .el-form-item__content {
  align-items: flex-start !important;
}

::v-deep .err-120 .el-form-item__error {
  padding-left: 120px !important;
}
.button {
  > div {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    > div {
      margin-left: 6px;
      text-decoration: underline;
      color: #409eff;
    }
  }
}
</style>
