
<!-- 采购计划策略弹出层 -->
<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">{{t('ts.规则').replace('ts.','')}}</div>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="t('ts.代码').replace('ts.','')" prop="strategyCode">
                <el-input key="strategyCode"
                  v-model="formData.strategyCode"
                  :placeholder="t('ts.请输入代码').replace('ts.','')"
                  clearable
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="t('ts.名称').replace('ts.','')" prop="name">
                <el-input key="name" v-model="formData.name" :placeholder="t('ts.请输入名称').replace('ts.','')" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="t('ts.描述').replace('ts.','')" prop="description">
                <el-input key="description" v-model="formData.description" :placeholder="t('ts.请输入描述').replace('ts.','')" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="t('ts.优先级').replace('ts.','')" prop="priority">
                <el-input-number key="priority" v-model="formData.priority" :min="0" :disabled="formData.name=='默认规则'&&formType=='update'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="t('ts.状态').replace('ts.','')" prop="status">
                <el-switch key="status" v-model="formData.status" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 规则条件 -->
        <div key="规则条件" class="item mt-20px">
          <div key="规则条件title" class="title">{{t('ts.规则条件').replace('ts.','')}}</div>
          <el-row key="规则条件row">
            <el-col :span="24" v-for="(item, index) in formData.condition" :key="'规则条件row'+index">
              <!-- 供应商类型 -->
              <el-form-item key="供应商类型formItem"
                v-if="item.ParamCode == 'SupplierType'"
                :label="t('ts.供应商类型').replace('ts.','')"
                class="flex-top err-120"
              >
                <el-select key="供应商类型Operator"
                  v-model="item.Operator"
                  :placeholder="t('ts.请选择范围').replace('ts.','')"
                  style="width: 110px; margin-right: 10px"
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                >
                  <el-option
                    :label="t(`ts.${cur.label}`).replace('ts.','')"
                    :value="cur.value"
                    v-for="cur in options.supplierTypeRangeOptions"
                    :key="'供应商类型Operator'+cur.value"
                  />
                </el-select>
                <el-select key="供应商类型Value"
                  v-model="item.Value"
                  :placeholder="t('ts.请选择供应商类型').replace('ts.','')"
                  style="flex: 1"
                  clearable
                  @change="changeSupplierType"
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                >
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.SUPPLIER_TYPE)"
                    :key="'供应商类型Value'+dict.value"
                    :label="t(`ts.${dict.label}`).replace('ts.','')"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <!-- 供应商 -->
              <el-form-item key="供应商formItem"
                v-else-if="item.ParamCode == 'SupplierCode'"
                :label="t('ts.供应商').replace('ts.','')"
                class="err-120"
              >
                <el-select key="供应商Operator"
                  v-model="item.Operator"
                  :placeholder="t('ts.请选择范围').replace('ts.','')"
                  style="width: 110px; margin-right: 10px"
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                >
                  <el-option
                    :label="t(`ts.${cur.label}`).replace('ts.','')"
                    :value="cur.value"
                    v-for="cur in options.supplierRangeOptions"
                    :key="'供应商Operator'+cur.value"
                  />
                </el-select>
                <el-select key="供应商Value"
                  v-model="item.Value"
                  :placeholder="t('ts.请选择供应商').replace('ts.','')"
                  style="flex: 1"
                  clearable
                  multiple
                  collapse-tags
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                >
                  <el-option
                    v-for="cur in options.supplierList"
                    :key="'供应商Value'+cur.code"
                    :label="t(`ts.${cur.name}`).replace('ts.','')"
                    :value="cur.code"
                  />
                </el-select>
              </el-form-item>
              <!-- 星期几 -->
              <el-form-item key="星期几formItem"
                v-else-if="item.ParamCode == 'Weekday'"
                :label="t('ts.星期几').replace('ts.','')"
                class="flex-top err-120"
              >
                <el-select key="星期几Operator"
                  v-model="item.Operator"
                  placeholder="请选择范围"
                  style="width: 110px; margin-right: 10px"
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                >
                  <el-option
                  :label="t(`ts.${cur.label}`).replace('ts.','')"
                  :value="cur.value"
                    v-for="cur in options.weekRangeOptions"
                    :key="'星期几Operator'+cur.value"
                  />
                </el-select>
                <div class="checkbox">
                  <el-checkbox-group v-model="item.Value">
                    <el-checkbox
                      :label="t(`ts.${cur.label}`).replace('ts.','')"
                      v-for="cur in options.weekOptions"
                      :key="'星期几Value'+cur.value"
                      :disabled="formData.name=='默认规则'&&formType=='update'"
                    />
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 规则配置 -->
        <div class="item mt-20px" key="规则配置">
          <div class="title" key="规则配置title">{{t('ts.规则配置').replace('ts.','')}}</div>
          <el-row key="规则配置Row">
            <!-- 开始时间 -->
            <el-col :span="24" key="规则配置Col">
              <!-- 开始时间 -->
              <el-form-item key="开始时间formItem" :label="t('ts.开始时间').replace('ts.','')" prop="BeginTime">
                <el-time-select key="开始时间time"
                  v-model="formData.configuration.BeginTime"
                  start="00:00"
                  end="23:59"
                  step="00:15"
                  :placeholder="t('ts.请选择开始时间').replace('ts.','')"
                  style="width: 100%"
                />
              </el-form-item>
              <!-- 结束时间 -->
              <el-form-item key="结束时间formItem" :label="t('ts.结束时间').replace('ts.','')" prop="EndTime">
                <el-time-select key="结束时间time"
                  v-model="formData.configuration.EndTime"
                  start="00:00"
                  end="23:59"
                  step="00:15"
                  :placeholder="t('ts.请选择结束时间').replace('ts.','')"
                  style="width: 100%"
                />
              </el-form-item>
              <!-- 仓库 -->
              <el-form-item key="仓库formItem" :label="t('ts.仓库').replace('ts.','')" prop="WarehouseCode">
                <el-select key="仓库"
                  v-model="formData.configuration.WarehouseCode"
                  :placeholder="`${t('ts.请选择').replace('ts.','')}${
                    formData.configuration.WarehouseCode == 'WarehouseCode'
                      ? '仓库'
                      : formData.configuration.WarehouseCode == 'AreaCode'
                      ? '库区'
                      : formData.configuration.WarehouseCode == 'LocationGroupCode'
                      ? '库位组'
                      : formData.configuration.WarehouseCode == 'LocationCode'
                      ? '库位'
                      : ''
                  }`"
                  clearable
                >
                  <el-option
                    v-for="cur in options.warehouseList"
                    :key="'仓库'+cur.code"
                    :label="cur.code"
                    :value="cur.code"
                  />
                </el-select>
              </el-form-item>
              <!-- 月台 -->
              <el-form-item key="月台formItem" :label="t('ts.月台').replace('ts.','')" prop="DockCode">
                <el-select key="月台"
                  v-model="formData.configuration.DockCode"
                  :placeholder="t('ts.请选择月台').replace('ts.','')"
                  clearable
                >
                  <el-option
                    v-for="cur in options.dockList"
                    :key="'月台'+cur.code"
                    :label="cur.code"
                    :value="cur.code"
                  />
                </el-select>
              </el-form-item>
              <!-- 在途库位 -->
              <el-form-item key="在途库位formItem" :label="t('ts.在途库位').replace('ts.','')" prop="OnTheWayLocationCode">
                <el-select key="在途库位"
                  v-model="formData.configuration.OnTheWayLocationCode"
                  :placeholder="t('ts.请选择在途库位').replace('ts.','')"
                  clearable
                  filterable
                  :filter-method="filterMethodFromLocation"
                >
                  <el-option
                    v-for="cur in options.locationList"
                    :key="'在途库位'+cur.code"
                    :label="cur.code"
                    :value="cur.code"
                  />
                </el-select>
              </el-form-item>
              <!-- 收货人 -->
              <el-form-item key="收货人formItem" :label="t('ts.收货人').replace('ts.','')" prop="Receiver">
                <el-input key="收货人" v-model="formData.configuration.Receiver" :placeholder="t('ts.请输入收货人名称').replace('ts.','')" clearable />
              </el-form-item>
              <!-- 在途库位 -->
              <el-form-item key="联系电话formItem" :label="t('ts.联系电话').replace('ts.','')"  prop="configuration.PhoneNumber">
                <el-input key="联系电话" v-model="formData.configuration.PhoneNumber" :placeholder="t('ts.请输入联系电话').replace('ts.','')" clearable />
              </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 { getWarehouseList } from '@/api/wms/warehouse'
import { getDockList } from '@/api/wms/dock'
import { getLocationList } from '@/api/wms/location'
import * as RuleApi from '@/api/wms/rule'
import { isString } from '@/utils/is'
import {validateHanset} from '@/utils/validator'

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: '' },
    // 星期几
    { ParamCode: 'Weekday', Operator: 'IN', Value: [] }
  ],
  configuration: {
    // 开始时间
    BeginTime: '',
    // 结束时间
    EndTime: '',
    // 仓库代码
    WarehouseCode: '',
    // 月台代码
    DockCode: '',
    // 在途库位代码
    OnTheWayLocationCode: '',
    // 收货人
    Receiver: '',
    // 联系电话
    PhoneNumber: ''
  }
})

// 验证规则
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' }],
  'configuration.PhoneNumber': [{ max: 11, message: '不得超过11个字符', trigger: 'blur' },
  {message: '请输入正确格式的电话', trigger: 'blur' ,validator:validateHanset}]
})

// 所有的范围类型
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('IN', 'NOT IN'),
  //供应商列表
  supplierList: [],
  // 星期几范围下拉框列表
  weekRangeOptions: formatRangeOptions('IN', 'NOT IN'),
  //星期几列表
  weekOptions: [
    { value: 1, label: '星期一' },
    { value: 2, label: '星期二' },
    { value: 3, label: '星期三' },
    { value: 4, label: '星期四' },
    { value: 5, label: '星期五' },
    { value: 6, label: '星期六' },
    { value: 7, label: '星期日' }
  ],
  //仓库列表
  warehouseList: [],
  //月台列表
  dockList: [],
  //在途库位列表
  locationList: [],
  originLocationList: []
})
// 弹窗按钮
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 getFormWarehouseList = async () => {
  options.warehouseList = await getWarehouseList()
}
// 获取月台列表
const getFormDockList = async () => {
  options.dockList = await getDockList()
}
const filterMethodFromLocation = (query: string) => {
  if (query) {
    options.locationList = options.originLocationList.filter((item) => {
      return item?.code.includes(query)
    })
  } else {
    options.locationList = [...options.originLocationList]
  }
}
// 获取库位列表
const getFormLocationList = async () => {
  if(!options.locationList || options.locationList.length==0){
    options.originLocationList = await getLocationList({ type: 'TRANSPORT' })
    options.locationList = [...options.originLocationList]
  }else{
    options.locationList = [...options.originLocationList]
  }
}

getFormSupplierList()
getFormWarehouseList()
getFormDockList()


/** 打开弹窗 */
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)
        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) // 关闭
    ]
  }
  getFormLocationList()
}
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
  }
  // 提交请求
  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: '' },
      // 星期几
      { ParamCode: 'Weekday', Operator: 'IN', Value: [] }
    ],
    configuration: {
      // 开始时间
      BeginTime: '',
      // 结束时间
      EndTime: '',
      // 仓库代码
      WarehouseCode: '',
      // 月台代码
      DockCode: '',
      // 在途库位代码
      OnTheWayLocationCode: ''
    }
  }
}
</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>
