<template>
  <a-modal :open="visible" title="新增物料信息" cancelText="取消" okText="提交" @ok="submit" @cancel="cancel" :width='720'>
    <a-form ref="formRef" :model="formState" :rules="formRules" layout="vertical">
      <div>
        <page-layout>
          <!-- <a-row :gutter="[0, 0]"> -->
            <!-- <a-col :span="24"> -->
              <a-row :gutter="[16, 0]">
                <a-col :span="12">
                  <a-form-item ref="skuCode" label="物料编号" name="skuCode">
                    <a-input v-model:value="formState.skuCode" placeholder="请输入物料编号" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item ref="skuName" label="物料名称" name="skuName">
                    <a-input v-model:value="formState.skuName" placeholder="请输入物料名称" />
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="8">
                  <a-form-item ref="ext1" label="颜色" name="ext1">
                    <a-input v-model:value="formState.ext1" placeholder="请输入颜色" />
                  </a-form-item>
                </a-col> -->
                <!-- <a-col :span="8">
                    <a-form-item ref="fullQty" label="满盘数量" name="fullQty">
                      <a-input-number v-model:value="formState.fullQty" placeholder="请输入满盘数量" style="width: 100%" />
                    </a-form-item>
                  </a-col> -->

              </a-row>
              <a-row :gutter="[16, 0]">
                <a-col :span="12">
                  <a-form-item label="ABC分类" name="abc">
                    <a-select v-model:value="formState.abc" :options="skuAbc" placeholder="请选择ABC分类">
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item ref="categoryCode" label="物料种类" name="categoryCode">
                    <a-select v-model:value="formState.categoryCode" show-search placeholder="请选择物料种类"
                      style="width: 100%" :default-active-first-option="false" :show-arrow="false"
                      :filter-option="false" :not-found-content="null" :options="categoryCodeRef.data"
                      @search="fetchCategoryCode" @change="categoryCodeHandleChange">
                      <template v-if="categoryCodeRef.fetching" #notFoundContent>
                        <a-spin size="small" />
                      </template>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item ref="baseUnit" label="库存单位" name="baseUnit">
                    <a-input v-model:value="formState.baseUnit" placeholder="请选择库存单位" :disabled="true" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="使用标志" name="useFlag">
                    <a-switch v-model:checked="formState.useFlag" checked-children="启用" un-checked-children="禁用" />
                  </a-form-item>
                </a-col>
              </a-row>
              <!-- <a-row>
                <a-col :span="8">
                  <a-form-item label="换算单位" name="primaryUnit">
                    <a-select v-model:value="formState.primaryUnit" :options="skuPrimaryUnit" placeholder="请选择换算单位">
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item ref="rate" label="换算率" name="rate">
                    <a-input-number v-model:value="formState.rate" @change="valueChanged" placeholder="请选择换算率"
                      style="width: 100%" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item ref="stackType" label="垛形" name="stackType">
                    <a-input-number v-model:value="formState.stackType" placeholder="请选择垛形" style="width: 100%" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-item ref="ext2" label="转速" name="ext2">
                    <a-input v-model:value="formState.ext2" placeholder="请输入转速" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item ref="ext3" label="配置" name="ext3">
                    <a-input v-model:value="formState.ext3" placeholder="请输入配置" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item ref="ext1" label="颜色" name="ext1">
                    <a-input v-model:value="formState.ext1" placeholder="请输入颜色" />
                  </a-form-item>
                </a-col> -->
                <!-- <a-col :span="8">
                  <a-form-item ref="fullQty" label="满盘数量" name="fullQty">
                    <a-input-number v-model:value="formState.fullQty" placeholder="请输入满盘数量" style="width: 100%" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row> -->
                <a-row>
                <!-- <a-col :span="8">
                  <a-form-item ref="expire" label="有效期" name="expire">
                    <a-input-number v-model:value="formState.expire" placeholder="请选择有效期" style="width: 100%" />
                  </a-form-item>
                </a-col> -->
                
                <a-col :span="24">
                  <a-form-item ref="remark" label="备注" name="remark">
                    <a-textarea v-model:value="formState.remark" laceholder="请输入备注" />
                  </a-form-item>
                </a-col>
              </a-row>
            <!-- </a-col> -->
          <!-- </a-row> -->
        </page-layout>
      </div>
      <!-- <a-form-item ref="skuCode" label="物料编号" name="skuCode">
        <a-input v-model:value="formState.skuCode" placeholder="请输入物料编号" />
      </a-form-item>
      <a-form-item ref="skuName" label="物料名称" name="skuName">
        <a-input v-model:value="formState.skuName" placeholder="请输入物料名称" />
      </a-form-item>
      <a-form-item ref="ext1" label="条码" name="ext1">
        <a-input v-model:value="formState.ext1" placeholder="请输入条码" />
      </a-form-item>
      <a-form-item label="ABC分类" name="abc">
        <a-select v-model:value="formState.abc" :options="skuAbc" placeholder="请选择ABC分类">
        </a-select>
      </a-form-item>
      <a-form-item ref="categoryCode" label="种类编号" name="categoryCode">
        <a-select v-model:value="formState.categoryCode" show-search placeholder="请选择种类编号" style="width: 100%"
          :default-active-first-option="false" :show-arrow="false" :filter-option="false" :not-found-content="null"
          :options="categoryCodeRef.data" @search="fetchCategoryCode" @change="categoryCodeHandleChange">
          <template v-if="categoryCodeRef.fetching" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </a-form-item>
      <a-form-item ref="baseUnit" label="库存单位" name="baseUnit">
        <a-input v-model:value="formState.baseUnit" placeholder="请选择库存单位" :disabled="true" />
      </a-form-item>
      <a-form-item label="换算单位" name="primaryUnit">
        <a-select v-model:value="formState.primaryUnit" :options="skuPrimaryUnit" placeholder="请选择换算单位">
        </a-select>
      </a-form-item>
      <a-form-item ref="rate" label="换算率" name="rate">
        <a-input-number v-model:value="formState.rate" @change="valueChanged" placeholder="请选择换算率"
          style="width: 100%" />
      </a-form-item>
      <a-form-item ref="stackType" label="垛形" name="stackType">
        <a-input-number v-model:value="formState.stackType" placeholder="请选择垛形" style="width: 100%" />
      </a-form-item>
      <a-form-item ref="ext2" label="库存高限" name="ext2">
        <a-input v-model:value="formState.ext2" placeholder="请选择库存高限" />
      </a-form-item>
      <a-form-item ref="ext3" label="库存低限" name="ext3">
        <a-input v-model:value="formState.ext3" placeholder="请选择库存低限" />
      </a-form-item>
      <a-form-item ref="fullQty" label="满盘数量" name="fullQty">
        <a-input-number v-model:value="formState.fullQty" placeholder="请输入满盘数量" style="width: 100%" />
      </a-form-item>
      <a-form-item ref="expire" label="有效期" name="expire">
        <a-input-number v-model:value="formState.expire" placeholder="请选择有效期" style="width: 100%" />
      </a-form-item>

      <a-form-item label="使用标志" name="useFlag">
        <a-switch v-model:checked="formState.useFlag" checked-children="启用" un-checked-children="禁用" />
      </a-form-item>

      <a-form-item ref="remark" label="备注" name="remark">
        <a-textarea v-model:value="formState.remark" laceholder="请输入备注" />
      </a-form-item> -->
    </a-form>
  </a-modal>
</template>
<script>
    import {
    message
  } from '@hwork/ant-design-vue';
  import {
    save
  } from "@/api/wms/sku";

  import {
    getSkuCategoryListByCode,
  } from "@/api/wms/skuCategory";

  import {
    defineComponent,
    reactive,
    ref,
    toRaw
  } from "vue";
  import {
    debounce
  } from 'lodash-es';
  export default defineComponent({
    props: {
      visible: {
        type: Boolean,
      },
    },
    emit: ["close"],
    setup(props, context) {

      const formRef = ref();

      const state = reactive({

      });

      const formState = reactive({
        baseUnit: "件",
        useFlag: true,
        rate:1,
        abc:"A类"
      });

      const formRules = {
        skuCode: [{
          required: true,
          message: '请输入物料编号',
          trigger: 'blur'
        }],
        skuName: [{
          required: true,
          message: '请输入物料名称',
          trigger: 'blur'
        }],
         ext1: [{
           required: true,
           message: '请输入颜色',
           trigger: 'blur'
         }],
         ext2: [{
           required: true,
           message: '请输入转速',
           trigger: 'blur'
         }],
         ext3: [{
           required: true,
           message: '请输入配置',
           trigger: 'blur'
         }],
        /* abc: [{
          required: true,
          message: '请输入ABC分类',
          trigger: 'blur'
        }], */
        // skuType: [{
        //   required: false,
        //   message: '请输入物料分类',
        //   trigger: 'blur'
        // }],
        categoryCode: [{
          required: true,
          message: '请输入种类名称',
          trigger: 'blur'
        }],
        // baseUnit: [{
        //   required: true,
        //   message: '请输入库存单位',
        //   trigger: 'blur'
        // }],
         primaryUnit: [{
          required: true,
           message: '请输入换算单位',
          trigger: 'blur'
        }],
        // rate: [{
        //   required: true,
        //   message: '请输入换算率',
        //   trigger: 'blur'
        // }],
        // stackType: [{
        //   required: true,
        //   message: '请输入垛形',
        //   trigger: 'blur'
        // }],
        // stockH: [{
        //   required: true,
        //   message: '请输入库存高限',
        //   trigger: 'blur'
        // }],
        // stockL: [{
        //   required: true,
        //   message: '请输入库存低限',
        //   trigger: 'blur'
        // }],
        fullQty: [{
          required: true,
          message: '请输入满盘数量',
          trigger: 'blur',
          type: 'number'
        }],
       /* expire: [{
          required: true,
          message: '请输入有效期',
          trigger: 'blur',
          type: 'number'
        }], */
        // useFlag: [{
        //   required: true,
        //   message: '请输入使用标志',
        //   type: 'number',
        //   trigger: 'blur',
        // }],
      };

      const saveKey = "save";
      const categoryCodeRef = ref({
        data: [],
        value: "",
        fetching: false
      });

      const valueChanged = (e) => {
        formState.rate = (formState.rate).toFixed(2);
      }

      const categoryCodeHandleChange = val => {
        console.log("categoryNameHandleChange", val);
        categoryCodeRef.value.value = val;
        console.log("categoryCodeRef.data", categoryCodeRef.value.data);
        if (val.length > 0) {
          categoryCodeRef.value.data.forEach((skuCategory) => {
            console.log(skuCategory)
            if (skuCategory.value === val) {
              formState.categoryName = skuCategory.label;
            }
          })
        }
      };

      let lastFetchId = 0;

      const fetchCategoryCode = debounce(value => {
        console.log('fetching categoryCode', value);
        lastFetchId += 1;
        const fetchId = lastFetchId;
        console.log("categoryCodeRef.value", categoryCodeRef.value)
        categoryCodeRef.value.data = [];
        categoryCodeRef.value.fetching = true;
        getSkuCategoryListByCode({
          "categoryCode": value
        }).then(
          response => {
            console.log("response", response)
            if (response.success === true && response.data.length > 0) {
              if (fetchId !== lastFetchId) {
                return;
              }
              let data = response.data.map(skuCategory => ({
                label: `${skuCategory.categoryName}`,
                value: skuCategory.categoryCode,
              }));

              categoryCodeRef.value.data = data;
              categoryCodeRef.value.fetching = false;
            } else {
              //失败，弹窗提示没找到
              message.error({
                content: "没有找到相关数据"
              })
            }
            console.log("categoryCodeRef.value.data", categoryCodeRef.value.data)
          }
        )
      }, 300);

      const skuAbc = ref([{
        value: 'A类',
        label: 'A类',
      }, {
        value: 'B类',
        label: 'B类',
      }, {
        value: 'C类',
        label: 'C类',
      }]);

      const skuCategoryName = ref([{
          value: '成品',
          label: '成品',
        },
        {
          value: '原材料',
          label: '原材料',
        },
      ]);

      const skuPrimaryUnit = ref([{
          value: '台',
          label: '台',
        },
        {
          value: '箱',
          label: '箱',
        },
        {
          value: '盒',
          label: '盒',
        },
      ]);

      const submit = (e) => {
        formRef.value
        .validate()
        .then(() => {
            message.loading({
              content: '提交中...',
              key: saveKey
            });
            save(toRaw(formState)).then((response) => {
              if (response.success) {
                message.success({
                  content: '保存成功',
                  key: saveKey,
                  duration: 1
                }).then(() => {
                  cancel();
                });
              } else {
                message.error({
                  content: response.msg,
                  key: saveKey,
                  duration: 1
                }).then(() => {
                  // cancel();
                });
              }
            });
          })
          .catch(error => {
            console.log('error', error);
          });
      };

      const cancel = (e) => {
        formRef.value.resetFields();
        context.emit("close", false);
      };

      // loadUser();

      return {
        state,
        submit,
        cancel,
        formRef,
        formState,
        formRules,
        valueChanged,
        skuAbc,
        skuCategoryName,
        skuPrimaryUnit,
        categoryCodeRef,
        categoryCodeHandleChange,
        fetchCategoryCode,
        labelCol: {
          span: 8
        },
        wrapperCol: {
          span: 12
        },
      };
    },
  });
</script>
