
<!-- 采购计划策略弹出层 -->
<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 key="规则row">
            <el-col :span="24" key="代码col">
              <el-form-item key="formItem" :label="t('ts.代码').replace('ts.','')" prop="strategyCode">
                <el-input key="代码input"
                  v-model="formData.strategyCode"
                  :placeholder="t('ts.请输入代码').replace('ts.','')"
                  clearable
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="24" key="名称col">
              <el-form-item key="名称formItem" :label="t('ts.名称').replace('ts.','')" prop="name">
                <el-input key="名称name" v-model="formData.name" :placeholder="t('ts.请输入名称').replace('ts.','')" clearable :disabled="formData.name=='默认规则'&&formType=='update'"/>
              </el-form-item>
            </el-col>
            <el-col :span="24" key="描述col">
              <el-form-item key="描述formItem" :label="t('ts.描述').replace('ts.','')" prop="description">
                <el-input key="描述input" v-model="formData.description" :placeholder="t('ts.请输入描述').replace('ts.','')" clearable :disabled="formData.name=='默认规则'&&formType=='update'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" key="优先级col">
              <el-form-item key="优先级formItem" :label="t('ts.优先级').replace('ts.','')" prop="priority">
                <el-input-number key="优先级input" v-model="formData.priority" :min="1" :disabled="formData.name=='默认规则'&&formType=='update'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" key="状态col">
              <el-form-item key="状态formItem" :label="t('ts.状态').replace('ts.','')" prop="status">
                <el-switch key="状态switch" v-model="formData.status" :disabled="formData.name=='默认规则'&&formType=='update'"/>
              </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" label="受入地" class="err-120" v-if="index==0">
                <el-select key="受入地Operator"
                  v-model="item.Operator"
                  placeholder="请选择范围"
                  style="width: 110px; margin-right: 10px"
                  :disabled="formData.name=='默认规则'&&formType=='update'"
                  @change="OperatorChange($event,item)"
                >
                  <el-option
                    :label="cur.label"
                    :value="cur.value"
                    v-for="cur in options.WarehouseCodeRangeOptions"
                    :key="'受入地Operator'+cur.value"
                  />
                </el-select>
                <el-input key="受入地Value" style="flex:1" placeholder="请选择受入地"  v-model="item.Value" @blur="blurWarehouseByCodes">
                  <template #suffix>
                    <el-button :disabled="formData.name=='默认规则'&&formType=='update'" type="text" plain style="color:var(--el-button-text-color)" @click="searchWarehouse">
                      <Icon icon="ep:search" class="mr-5px" /> 
                    </el-button> 
                  </template>
                </el-input>
              </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'"
                  @change="OperatorChange($event,item)"
                >
                  <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-input key="供应商代码Value" style="flex:1" placeholder="请选择供应商代码" v-model="item.Value" @blur="blurSupplierCode">
                  <template #suffix>
                    <el-button :disabled="formData.name=='默认规则'&&formType=='update'" type="text" plain style="color:var(--el-button-text-color)" @click="searchSupplier">
                      <Icon icon="ep:search" class="mr-5px" /> 
                    </el-button> 
                  </template>
                </el-input>
              </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="DockCode">
                <el-input key="月台Value" style="flex:1" placeholder="请选择月台" v-model="formData.configuration.DockCode" @blur="blurDockCode">
                  <template #suffix>
                    <el-button :disabled="formData.name=='默认规则'&&formType=='update'" type="text" plain style="color:var(--el-button-text-color)" @click="searchDockCode">
                      <Icon icon="ep:search" class="mr-5px" /> 
                    </el-button> 
                  </template>
                </el-input>
              </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-form-item key="是否上架formItem" :label="t('ts.是否上架').replace('ts.','')"  prop="configuration.PutAway">
                  <el-switch
                    v-model="formData.configuration.PutAway"
                    active-value="TRUE"
                    inactive-value="FALSE"
                  />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <template #footer>
      <!-- 按钮-->
      <TableHead :HeadButttondata="Butttondata" @buttonBaseClick="buttonBaseClick" />
    </template>
  </Dialog>
  <SearchTable
    ref="searchTableRef"
    @searchTableSuccess="searchTableSuccess"
  />
</template>
<script setup lang="ts">
import * as defaultButtons from '@/utils/disposition/defaultButtons'
defineOptions({ name: 'SupplieDeliveryStrategyAddForm' })
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import * as RuleApi from '@/api/wms/rule'
import { isString } from '@/utils/is'
import { validateHanset } from '@/utils/validator'


import * as WarehouseApi from '@/api/wms/warehouse'
import { Warehouse } from '@/views/wms/basicDataManage/factoryModeling/warehouse/warehouse.data'
import * as SupplierApi from '@/api/wms/supplier'
import { Supplier } from '@/views/wms/basicDataManage/supplierManage/supplier/supplier.data'
import * as DockApi from '@/api/wms/dock'
import { Dock } from '@/views/wms/basicDataManage/factoryModeling/dock/dock.data'

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: 'WarehouseCode', Operator: 'IN', Value: '',ScreenOperator:'in' },
    // 供应商代码
    { ParamCode: 'SupplierCode', Operator: 'IN', Value: '' ,ScreenOperator:'in'},
  ],
  configuration: {
    // 开始时间
    BeginTime: '',
    // 结束时间
    EndTime: '',
    // 月台代码
    DockCode: '',
    // 收货人
    Receiver: '',
    // 联系电话
    PhoneNumber: '',
    // 是否上架
    PutAway:'TRUE'
  }
})

// 验证规则
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: t('ts.等于'),screenValue:'=='},
  { value: '!=', label: t('ts.不等于'),screenValue:'!='},
  { value: '>', label: t('ts.大于'),screenValue:'>' },
  { value: '<', label:  t('ts.小于'),screenValue:'<'},
  { value: '>=', label: t('ts.大于等于'),screenValue:'>='},
  { value: '<=', label: t('ts.小于等于'),screenValue:'<='},
  { value: 'IN', label:  t('ts.包含'),screenValue:'in' },
  { value: 'NOT IN', label: t('ts.不包含'),screenValue:'notIn'},
  { value: 'NULL', label: t('ts.是空'),screenValue:'isNull'},
  { value: 'NOT NULL', label: t('ts.不是空'),screenValue:'isNotNull'}
]
const formatRangeOptions = (...rest) => {
  // 交集
  let result = rangeOptions.filter((aItem) => rest.some((bItem) => aItem.value === bItem))
  return result
}
// 下拉框列表集合
const options = reactive({
  // 供应商范围下拉框列表
  WarehouseCodeRangeOptions: formatRangeOptions('IN', 'NOT IN'),
  // 供应商范围下拉框列表
  supplierRangeOptions: formatRangeOptions('IN', 'NOT IN'),
  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 open = async (type: string, strategyCode: string, id?: number) => {
  formStrategyCode.value = strategyCode
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  warehouseCodeObj.value =""
  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(',')
        //   }
        // })
        warehouseCodeObj.value = formData.value.condition.find(item => item['ParamCode'] == 'WarehouseCode') || ''
      }
      if (data.configuration) {
        formData.value.configuration = JSON.parse(data.configuration)
      }
      querySupplierParams.value.type = formData.value?.condition[0]?.Value || ''
    } 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
  console.log(555,formData.value)
  // 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,
        ScreenOperator:item.ScreenOperator,
        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: 'WarehouseCode', Operator: 'IN', Value: '',ScreenOperator:'in' },
      // 供应商
      { ParamCode: 'SupplierCode', Operator: 'IN', Value: '' ,ScreenOperator:'in'},
    ],
    configuration: {
      // 开始时间
      BeginTime: '',
      // 结束时间
      EndTime: '',
      // 月台代码
      DockCode: '',
      // 是否上架
      PutAway:'TRUE'
    }
  }
}

const searchTableRef = ref()
// 仓库
const searchWarehouse = ()=>{
  searchTableRef.value.open(
    '请选择仓库',
    Warehouse.allSchemas,
    WarehouseApi.getWarehousePage,
    'WarehouseCode',
    'code',
    true,
    undefined,
    undefined,
    undefined
  )
}
// 选择供应商
const searchSupplier = () => {
  searchTableRef.value.open(
    '请选择供应商',
    Supplier.allSchemas,
    SupplierApi.getSupplierPage,
    'SupplierCode',
    'code',
    true,
    undefined,
    undefined,
    undefined
  )
}
const searchDockCode = () => {
  // if (!warehouseCodeStr.value) {
  //   message.warning('请选择受入地')
  //   return;
  // }
  let filters = []
  if (warehouseCodeObj.value?.Value) {
    filters = [{
      action: warehouseCodeObj.value.ScreenOperator,
      column: 'warehouseCode',
      value: warehouseCodeObj.value.Value
    }]
  }
  
  searchTableRef.value.open(
    '请选择月台',
    Dock.allSchemas,
    DockApi.getDockPage,
    'DockCode',
    'code',
    false,
    undefined,
    undefined,
    {
      isSearch: true,
      filters: filters
    }
  )
}
const warehouseCodeObj = ref()
const searchTableSuccess = (formField, searchField, val, type, row) => {
  if(formField=='WarehouseCode'){
    warehouseCodeObj.value = formData.value.condition.find(item => item['ParamCode'] == 'WarehouseCode')
    if(warehouseCodeObj.value){
      warehouseCodeObj.value.Value = val.map(item => (item['code'])).join(',')
      formData.value.configuration['DockCode']=''
    }
  } else if (formField=='SupplierCode') {
    let SupplierCode = formData.value.condition.find(item => item['ParamCode'] == 'SupplierCode')
    if(SupplierCode){
      SupplierCode.Value = val.map(item=>(item['code'])).join(',')
    }
  } else if (formField=='DockCode') {
    formData.value.configuration[formField] = val[0][searchField]
    formData.value.configuration.Receiver = val[0].contactPerson
    formData.value.configuration.PhoneNumber = val[0].contactPhone
  }
}
// 受入地失去焦点校验
const blurWarehouseByCodes = async ()=>{
  let WarehouseCode = formData.value.condition.find(item=>item['ParamCode']=='WarehouseCode')
  if(WarehouseCode&&WarehouseCode.Value){
    let verifyRes = await WarehouseApi.getWarehouseByCodes({
      codes:WarehouseCode.Value
    })
    console.log('事务类型verifyRes',verifyRes)
    if (verifyRes && verifyRes.length > 0) {
       const arr1 = WarehouseCode.Value.split(',')
       if (arr1.length != verifyRes.length) {
        const arr2 = verifyRes.map((item) => item.code)
        const str = [
          ...arr1.filter((item) => !arr2.includes(item)),
          ...arr2.filter((item) => !arr1.includes(item))
        ].join(',')
        message.alert('代码' + str + '没有找到对应数据')
        WarehouseCode.Value = ''
        formData.value.configuration.DockCode=''
        formData.value.configuration.Receiver=''
        formData.value.configuration.PhoneNumber=''
        return
      }
    } else {
      WarehouseCode.Value = ''
      formData.value.configuration.DockCode=''
      formData.value.configuration.Receiver=''
      formData.value.configuration.PhoneNumber=''
      message.alert('暂无数据')
    }
  }else{
    WarehouseCode.Value = ''
    formData.value.configuration.DockCode=''
    formData.value.configuration.Receiver=''
    formData.value.configuration.PhoneNumber=''
  }
}
// 供应商失去焦点
const blurSupplierCode = async ()=>{
  let SupplierCode = formData.value.condition.find(item=>item['ParamCode']=='SupplierCode')
  if(SupplierCode&&SupplierCode.Value){
    let verifyRes = await SupplierApi.getSupplierListByCodes({
      codes:SupplierCode.Value
    })
    console.log('事务类型verifyRes',verifyRes)
    if (verifyRes && verifyRes.length > 0) {
       const arr1 = SupplierCode.Value.split(',')
       if (arr1.length != verifyRes.length) {
        const arr2 = verifyRes.map((item) => item.code)
        const str = [
          ...arr1.filter((item) => !arr2.includes(item)),
          ...arr2.filter((item) => !arr1.includes(item))
        ].join(',')
        message.alert('代码' + str + '没有找到对应数据')
        SupplierCode.Value = ''
        return
      }
    } else {
      SupplierCode.Value = ''
      message.alert('暂无数据')
    }
  }else{
    SupplierCode.Value = ''
  }
}
// 月台失去焦点
const blurDockCode = async () => {
  if (formData.value.configuration.DockCode) {
    let filters = []
      if (warehouseCodeObj.value?.Value) {
      filters.push({
        action:  warehouseCodeObj.value.ScreenOperator,
        column: 'warehouseCode',
        value: warehouseCodeObj.value.Value
      })
    }
    if (formData.value.configuration.DockCode) {
      filters.push({
        action: '==',
        column: 'code',
        value: formData.value.configuration.DockCode
    })
    }
    let verifyRes = await DockApi.getDockPage({
      isSearch:true,  
      filters: filters
    })
    console.log('事务类型verifyRes',verifyRes)
    if (verifyRes.list && verifyRes.list.length > 0) {
    } else {
      formData.value.configuration.DockCode = ''
      message.alert('暂无数据')
    }
  }
    
}
const OperatorChange = (e, item) => {
  item.ScreenOperator =  rangeOptions.find((item) =>item.value === e)?.screenValue
}
</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>
