
<!-- 采购收货任务拆分策略弹出层 -->
<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible"  width="700px">
    <div class="p-20px m--10px" style="max-height: 80vh; overflow-y: auto">
      <!-- 规则 -->
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="140px"
        label-position="left"
      >
        <div class="item">
          <div class="title">规则</div>
          <el-row gutter="10">
            <el-col :span="24">
              <el-form-item label="代码" prop="strategyCode">
                <el-input
                  v-model="formData.strategyCode"
                  placeholder="请输入代码"
                  clearable
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="描述" prop="description">
                <el-input v-model="formData.description" placeholder="请输入描述" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先级" prop="priority">
                <el-input-number v-model="formData.priority" :min="0" :disabled="formData.name=='默认规则'&&formType=='update'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-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 gutter="10">
            <el-col :span="24" v-for="(item, index) in formData.condition" :key="index">
              <!-- 供应商类型 -->
              <el-form-item
                v-if="item.ParamCode == 'SupplierType'"
                label="供应商类型"
                class="flex-top err-120"
              >
                <el-select
                  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="cur.value"
                  />
                </el-select>
                <el-select
                  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="dict.value"
                  />
                </el-select>
              </el-form-item>
              <!-- 供应商 -->
              <el-form-item
                v-else-if="item.ParamCode == 'SupplierCode'"
                label="供应商"
                class="err-120"
              >
                <el-select
                  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="cur.value"
                  />
                </el-select>
                <el-select
                  v-model="item.Value"
                  placeholder="请选择供应商"
                  style="flex: 1"
                  clearable
                  multiple
                  collapse-tags
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                >
                  <el-option
                    v-for="cur in options.supplierList"
                    :key="cur.code"
                    :label="cur.name"
                    :value="cur.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 规则配置 -->
        <div class="item mt-20px">
          <div class="title">规则配置</div>
          <el-row gutter="10">
            <el-col :span="24">
              <el-form-item label="不拆分">
                <el-switch  v-model="formData.configuration.NotGroup"  active-value="TRUE" inactive-value="FALSE" @change="changeGroup"/>
              </el-form-item>
              <!-- 按零件拆分 -->
              <el-form-item  label="按零件拆分">
                <el-switch v-model="formData.configuration.ByItem"  active-value="TRUE" inactive-value="FALSE" @change="changeGroup"/>
              </el-form-item>
              <!-- 按库位拆分 -->
              <el-form-item  label="按库位拆分">
                <el-switch v-model="formData.configuration.ByLocation"  active-value="TRUE" inactive-value="FALSE" @change="changeGroup"/>
              </el-form-item>
              <!--按器具拆分-->
              <el-form-item label="按器具拆分">
                <el-switch  v-model="formData.configuration.ByContainer"  active-value="TRUE" inactive-value="FALSE" @change="changeGroup"/>
              </el-form-item>
              <!-- 每个任务明细数量 -->
              <el-form-item label="每个任务明细数量" v-show="false">
                <el-input-number v-model="formData.configuration.JobDetailCount" :min="0" />
              </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'
import { object } from 'vue-types'
import { isString } from '@/utils/is'
import { log } from 'console';

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: 'IN', Value: '' }
  ],
  configuration: {
    // 不拆分
    NotGroup: 'FALSE',
    // 按零件拆分
    ByItem: 'FALSE',
    // 按库位拆分
    ByLocation: 'TRUE',
    // 按器具拆分
    ByContainer: 'FALSE',
    // 每个任务明细数量
    JobDetailCount: 0
  }
})

// 验证规则
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' }]
})

// 所有的范围类型
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: [
    { value: 1, label: '标准' },
    { value: 2, label: '委外' },
    { value: 3, label: '其他' }
  ],
  // 供应商范围下拉框列表
  supplierRangeOptions: formatRangeOptions('IN', 'NOT IN'),
  //供应商列表
  supplierList: [
    { value: 1, label: '供应商1' },
    { value: 2, label: '供应商2' },
    { value: 3, label: '供应商3' }
  ]
})
// 弹窗按钮
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 querySupplierParams = ref({
  type: ''
})
// 获取供应商列表
const getFormSupplierList = async () => {
  options.supplierList = await getSupplierList(querySupplierParams.value)
}

// 选择供应商类型
const changeSupplierType = (e) => {
  querySupplierParams.value.type = e
  formData.value.condition[1].Value = []
  getFormSupplierList()
}

const changeGroup = () =>{
  if(formData.value.configuration.NotGroup == 'TRUE'){
    formData.value.configuration.ByItem = 'FALSE'
    formData.value.configuration.ByLocation = 'FALSE'
    formData.value.configuration.ByContainer = 'FALSE'
  }else{
    if(formData.value.configuration.ByItem == 'TRUE'){
      formData.value.configuration.NotGroup == 'FALSE'
    }
    if(formData.value.configuration.ByLocation == 'TRUE'){
      formData.value.configuration.NotGroup == 'FALSE'
    }
    if(formData.value.configuration.ByContainer == 'TRUE'){
      formData.value.configuration.NotGroup == 'FALSE'
    }
  }
}
getFormSupplierList()

/** 打开弹窗 */
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) // 关闭
        ]
        console.log(Butttondata)
      } else {
        Butttondata.value = [
          defaultButtons.formSaveBtn(null), // 保存
          defaultButtons.formCloseBtn(null) // 关闭
        ]
      }
      if (data.condition) {
        formData.value.condition = JSON.parse(data.condition)
        formData.value.condition.forEach((item, index) => {
          if (item.Operator == 'IN' || item.Operator == 'NOT IN') {
            item.Value = item.Value.split(',')
          }
        })
      }
      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 submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if(formData.value.priority == 0){
    message.error('优先级不可以为0')
    return
  }
  let list = Object.values(formData.value.configuration)
  let onlyOne = list.filter((item) => {
    return item == 'TRUE'
  })
  if (onlyOne?.length != 1) {
    message.error('只能选择一种拆分方式')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const arr = formData.value.condition.map(item=> {
       let str = item.Value
       if(isString(item.Value)){
        if(item.Value.indexOf('，'>-1)){
        str = item.Value.split('，').join(',')
        }
      }
      if ((item.Operator == 'IN' || item.Operator == 'NOT IN')&& Array.isArray(item.Value)) {
        str = item.Value.join(',')
      }
     
      return {
        ParamCode:item.ParamCode,
        Operator:item.Operator,
        Value:str
      }
    })
    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(arr),
      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: 'IN', Value: '' }
    ],
    configuration: {
      // 不拆分
      NotGroup: 'FALSE',
      // 按零件拆分
      ByItem: 'FALSE',
      // 按库位拆分
      ByLocation: 'TRUE',
      // 按器具拆分
      ByContainer: 'FALSE',
      // 每个任务明细数量
      JobDetailCount: 0
    }
  }
}


</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;
}
</style>
