<template>
  <view class="c-card">
    <u-form
      labelPosition="left"
      :model="model1"
      :rules="rules"
      ref="form"
      :labelWidth="100"
      :labelStyle="{ padding: '0rpx 10rpx' }"
      :errorType="'border-bottom'"
    >
      <u-form-item
        :prop="`formData.${item.key}`"
        :label="item.name"
        :required="item.required"
        v-for="(item, index) in formAttrList"
        :key="index"
        @click="item.fn"
      >
        <u-textarea
          v-if="item.type === 'textarea'"
          v-model="(model1.formData as any)[item.key]"
          :placeholder="`请输入${item.name}`"
        ></u-textarea>
        <u-input
          v-if="item.type === 'select' || item.type === 'input'"
          v-model="(model1.formData as any)[item.key]"
          :placeholder="`请${item.type === 'select' ? '选择' : '输入'}${
            item.name
          }`"
          :clearable="true"
          :customStyle="{}"
          border="none"
          :disabled="item.type === 'select'"
          :disabledColor="['收货分类'].indexOf(item.name) > -1?'#ffffff':'#f5f7fa'"
          @change="(e:any) => {handleInput(e, item)}"
        >
          <template #suffix>
            <text>
              {{ item.unit }}
            </text>
          </template>
        </u-input>
        <template #right v-if="item.type === 'select'">
          <u-icon name="arrow-right"></u-icon>
        </template>
      </u-form-item>
    </u-form>
    <block v-for="(item, index) in formAttrList" :key="index">
      <u-action-sheet
        v-if="item.type === 'select'"
        :actions="contrlModalParams[item.childKey].list"
        :title="contrlModalParams[item.childKey].title"
        :show="contrlModalParams[item.childKey].isShow"
        @select="(v: any) => handleSelect(item.childKey, v)"
        @close="contrlModalParams[item.childKey].isShow = false"
        :closeOnClickAction="true"
        :scroll="true"
      ></u-action-sheet>
    </block>
  </view>
  <view class="btn-box">
    <u-button type="primary" text="保存" @click="save()"></u-button>
  </view>
</template>
<script setup lang="ts">
import { GoodsApi } from "@/services";
import { countDots } from "@/utils";
import valid from "@/utils/validate";
import { onLoad } from "@dcloudio/uni-app";
import _ from "underscore";
// 最低价 最高价 常用价格
const handleInput = (e: any, item: any) => {
  if (["minPrice", "maxPrice", "commonPrice"].indexOf(item.key) > -1) {
    const temp = e?.replace(valid.valid_decimal.pattern, "");
    if (countDots(temp).length > 1) {
      uni.showToast({
        title: "请输入正确的" + item.name,
        icon: "none",
      });
    }
    if (item.key === "maxPrice") {
      if (model1.formData.minPrice > model1.formData.maxPrice) {
        uni.showToast({
          title: `${item.name}应小于${model1.formData.maxPrice}`,
          icon: "none",
        });
        return;
      }
    }
    if (item.key === "commonPrice") {
      if (model1.formData.minPrice > -1 && model1.formData.maxPrice > -1) {
        if (
          temp < model1.formData.minPrice ||
          temp > model1.formData.maxPrice
        ) {
          uni.showToast({
            title: `${item.name}应在${model1.formData.minPrice}-${model1.formData.maxPrice}之间`,
            icon: "none",
          });
          return;
        }
      }
    }

    setTimeout(() => {
      model1.formData[item.key] = temp;
    }, 100);
  }
  if (item.key === "subtractNum") {
    const temp = e?.replace(valid.valid_decimal.pattern, "");
    if (
      model1.order.buttonType === 1 &&
      (parseInt(temp) > 100 || parseInt(temp) < 0)
    ) {
      uni.showToast({
        title: `${item.name}正确范围是0-100`,
        icon: "none",
      });
    }
    setTimeout(() => {
      model1.order[item.key] = temp;
    }, 100);
  }
};
const model1 = reactive<any>({
  formData: {},
});
const rules = ref({
  "formData.reProductsName": {
    type: "string",
    required: true,
    message: "请输入收货产品",
    trigger: ["blur", "change"],
  },
  "formData.reCategoryName": {
    type: "string",
    required: true,
    message: "请选择收货分类",
    trigger: ["blur", "change"],
  },
  // "formData.substationName": {
  //   type: "string",
  //   required: true,
  //   message: "请输入所属分站",
  //   trigger: ["blur", "change"],
  // },
  "formData.minPrice": {
    type: "number",
    required: true,
    message: "最低价为空或输入错误",
    trigger: ["blur", "change"],
  },
  "formData.maxPrice": {
    type: "number",
    required: true,
    message: "最高价为空或输入错误",
    trigger: ["blur", "change"],
  },
  "formData.commonPrice": {
    type: "number",
    required: true,
    message: "常用价格为空或输入错误",
    trigger: ["blur", "change"],
  },
});
const contrlModalParams = reactive<any>({
  reCategory: {
    isShow: false,
    title: "标题",
    list: [],
  },
});

const formAttrList = reactive<any>([
  {
    name: "收货产品",
    key: "reProductsName",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "收货分类",
    key: "reCategoryName",
    type: "select",
    childKey: "reCategory",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams.reCategory.isShow = true;
      contrlModalParams.reCategory.title = "收货分类";
    },
  },
  // {
  //   name: "所属分站",
  //   key: "substationName",
  //   type: "input",
  //   required: true,
  //   unit: "",
  // },
  {
    name: "最低价",
    key: "minPrice",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "最高价",
    key: "maxPrice",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "常用价格",
    key: "commonPrice",
    type: "input",
    required: true,
    unit: "",
  },
]);

const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "reCategory") {
    model1.formData.reCategoryName = v.name;
    model1.formData.reCategoryId = v.id;
  }
};

const form = ref();
const check = () => {
  return new Promise((resolve) => {
    form.value
      .validate()
      .then((res: boolean) => {
        resolve(res);
      })
      .catch((errors: any) => {
        resolve(false);
        uni.showToast({
          icon: "none",
          title: errors[0].message || "校验失败",
        });
      });
  });
};

const save = () => {
  if (model1.formData.minPrice > model1.formData.maxPrice) {
    uni.showToast({
      title: `最低价应小于${model1.formData.maxPrice}`,
      icon: "none",
    });
    return;
  }
  if (model1.formData.minPrice > -1 && model1.formData.maxPrice > -1) {
    const temp = model1.formData.commonPrice;
    if (temp < model1.formData.minPrice || temp > model1.formData.maxPrice) {
      uni.showToast({
        title: `常用价格应在${model1.formData.minPrice}-${model1.formData.maxPrice}之间`,
        icon: "none",
      });
      return;
    }
  }
  console.log(model1.formData);
  check().then((res) => {
    if (res) {
      startSave();
    }
  });
};
const startSave = () => {
  if (model1.formData.id) {
    GoodsApi.EditReceiveProduct(model1.formData).then((res) => {
      if (res.code === 200) {
        uni.navigateBack()
      }
    });
  } else {
    GoodsApi.addReProducts(model1.formData).then((res) => {
      if (res.code === 200) {
        uni.navigateBack()
      }
    });
  }
};

const getTypeList = () => {
  GoodsApi.allReCategory().then((res) => {
    if (res.code === 200) {
      contrlModalParams.reCategory.list = (res.data as any).map((item: any) => {
        return { ...item, name: item.reCategoryName };
      });
    }
  });
};

onMounted(() => {
  getTypeList();
});

onLoad((option) => {
  // 接收传递的标题参数
  const title = (option as any).title;
  if ((option as any).item) {
    model1.formData = JSON.parse((option as any).item);
    if (model1.formData.cardCode) {
      model1.formData.stockCardName = model1.formData.cardCode;
    }
  }

  // 设置页面标题
  uni.setNavigationBarTitle({
    title: title || '新增收货产品',
  });
});
</script>
<style lang="scss" scoped>
.c-card {
  background: #ffffff;
  // box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(5, 68, 37, 0.12);
  border-radius: 13rpx;
  margin: 30rpx 25rpx;
  padding: 0rpx 20rpx;
  ::v-deep .u-form-item {
    height: auto;
  }
  ::v-deep .u-form-item + .u-form-item {
    border-top: 1rpx solid rgba(233, 233, 233, 0.76);
  }
}
.btn-box {
  margin-top: 60rpx;
  display: flex;
  background: #ffffff;
  box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(0, 56, 93, 0.12);
  border-radius: 13rpx 13rpx 0rpx 0rpx;
  padding: 25rpx 50rpx;
  position: sticky;
  bottom: 0rpx;
  z-index: 999;
  ::v-deep button {
    border-radius: 43rpx;
  }
}
</style>
