<template>
  <view class="c-card">
    <u-form
      labelPosition="left"
      :model="model1"
      :rules="model1.formData.id ? rules1 : rules2"
      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
          :customStyle="{}"
          border="none"
          @change="(e:any) => {handleInput(e, item)}"
          :disabled="item.type === 'select'"
          :disabledColor="
            ['卡号', '供应商分类'].indexOf(item.name) > -1
              ? '#ffffff'
              : '#f5f7fa'
          "
          @clear="handleClear(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"
      ></u-action-sheet>
    </block>
  </view>
  <view class="btn-box">
    <u-button type="primary" text="保存" @click="save"></u-button>
  </view>

  <SmallModal
    :title="'确认作废旧卡号吗？'"
    :content="`确认作废${model1.formData.cardCode}后，不能恢复！`"
    :okText="'确认作废'"
    :isMain="true"
    :show="isShowCancelModal"
    @handleModal="(v:boolean) => {handleModal(v)}"
    @handleOk="handleOk()"
    @handleCancel="handleCancel()"
  />
</template>
<script setup lang="ts">
import { StockCardApi, SupplierApi } from "@/services";
import { formatDate } from "@/utils";
import { DeviceType, ImagesType, OrderType, StockCardType } from "@/utils/enum";
import valid from "@/utils/validate";
import { onLoad } from "@dcloudio/uni-app";
import _ from "underscore";
import SmallModal from "@/components/Modal/smallModal.vue";
const isShowCancelModal = ref(false);

const handleModal = (v: boolean) => {
  isShowCancelModal.value = v;
};
const handleOk = () => {
  handleCheck(true);
};
const handleCancel = () => {
  handleCheck(false);
};
const handleClear = (item: any) => {
  (model1.formData as any)[item.key] = "";
};
const handleInput = (e: any, item: any) => {
  if (item.key === "phone" || item.key === "bankNumber") {
    const temp = e?.replace(valid.valid_number, "");
    setTimeout(() => {
      model1.formData[item.key] = temp;
    }, 10);
  }
};
const model1 = reactive<any>({
  formData: {},
});
const rules1 = ref({
  "formData.name": {
    type: "string",
    required: true,
    message: "请输入供应商",
    trigger: ["blur", "change"],
  },
  "formData.supplierTypeName": {
    type: "string",
    required: true,
    message: "请选择供应商分类",
    trigger: ["blur", "change"],
  },
});
const rules2 = ref({
  "formData.stockCardName": {
    type: "string",
    required: true,
    message: "请选择卡号",
    trigger: ["blur", "change"],
  },
  "formData.name": {
    type: "string",
    required: true,
    message: "请输入供应商",
    trigger: ["blur", "change"],
  },
  "formData.supplierTypeName": {
    type: "string",
    required: true,
    message: "请选择供应商分类",
    trigger: ["blur", "change"],
  },
});
const contrlModalParams = reactive<any>({
  supplierType: {
    isShow: false,
    title: "标题",
    list: [],
  },
  stockCard: {
    isShow: false,
    title: "标题",
    list: [],
  },
});

const formAttrList = reactive<any>([
  {
    name: "基本信息",
    type: "text",
  },
  {
    name: "卡号",
    key: "stockCardName",
    type: "select",
    childKey: "stockCard",
    // required: true,
    fn: () => {
      if (contrlModalParams.stockCard.list.length === 0) {
        uni.showToast({ icon: "none", title: "当前无可用卡号,请添加入库卡" });
        return;
      }
      contrlModalParams.stockCard.isShow = true;
      contrlModalParams.stockCard.title = "卡号";
    },
  },
  {
    name: "供应商名称",
    key: "name",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "供应商分类",
    key: "supplierTypeName",
    type: "select",
    childKey: "supplierType",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams.supplierType.isShow = true;
      contrlModalParams.supplierType.title = "供应商分类";
    },
  },
  {
    name: "联系人",
    key: "contacts",
    type: "input",
    unit: "",
  },
  {
    name: "联系电话",
    key: "phone",
    type: "input",
    unit: "",
  },
  {
    name: "身份证号码",
    key: "card",
    type: "input",
    unit: "",
  },
  {
    name: "详细地址",
    key: "address",
    type: "input",
    unit: "",
  },
  {
    name: "银行卡信息",
    type: "text",
  },
  {
    name: "户名",
    key: "bankTitle",
    type: "input",
    unit: "",
  },
  {
    name: "银行名称",
    key: "bankName",
    type: "input",
    unit: "",
  },
  {
    name: "银行卡号",
    key: "bankNumber",
    type: "input",
    unit: "",
  },
  {
    name: "开户支行",
    key: "branchName",
    type: "input",
    unit: "",
  },
]);

const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "supplierType") {
    model1.formData.supplierTypeName = v.name;
    model1.formData.supplierTypeId = v.id;
  } else if (key === "stockCard") {
    model1.formData.stockCardName = v.name;
    model1.formData.stockCardId = 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.phone) {
    if (!valid.mobile.pattern.test(model1.formData.phone)) {
      uni.showToast({ icon: "none", title: "请输入正确的手机号" });
      return;
    }
  }
  if (model1.formData.card) {
    if (!valid.valid_id_card.pattern.test(model1.formData.card)) {
      uni.showToast({ icon: "none", title: "请输入正确的身份证号码" });
      return;
    }
  }

  if (
    model1.formData.cardCode &&
    model1.formData.stockCardName !== model1.formData.cardCode
  ) {
    handleModal(true);
  } else {
    handleCheck(false);
  }
};
const handleCheck = (v: boolean) => {
  check().then((res) => {
    if (res) {
      startSave(v);
    }
  });
};
const startSave = (v: boolean) => {
  if (model1.formData.id) {
    SupplierApi.updateSupplierUser({ ...model1.formData, delCard: v }).then(
      (res) => {
        if (res.code === 200) {
          // uni.navigateBack();
          uni.navigateBack({
            delta: 1,
            success: (res) => {
              uni.$emit("pricingParams", {
                name: model1.formData.name,
              });
            },
          });
        }
      }
    );
  } else {
    SupplierApi.addSupplierUser(model1.formData).then((res) => {
      if (res.code === 200) {
        uni.navigateBack();
      }
    });
  }
};

const getSupplierTypeList = () => {
  SupplierApi.getSupplierTypeList().then((res) => {
    if (res.code === 200) {
      contrlModalParams.supplierType.list = res.data;
    }
  });
};

const getStockCardList = () => {
  StockCardApi.getStockCardListInfo({ vincolante: StockCardType.Receive }).then(
    (res) => {
      if (res.code === 200) {
        contrlModalParams.stockCard.list = (res.data as any).map(
          (item: any) => {
            return { ...item, name: item.cardCode };
          }
        );
      }
    }
  );
};

onMounted(() => {
  getSupplierTypeList();
  getStockCardList();
});

onLoad((option: any) => {
  // 接收传递的标题参数
  const title = option.title;
  if (option.item) {
    SupplierApi.getSupplierUserList({ id: option.item }).then((res: any) => {
      if (res.code === 200) {
        if (res.data.length > 0) {
          model1.formData = res.data[0];
          if (model1.formData.cardCode) {
            model1.formData.stockCardName = model1.formData.cardCode;
          }
        } else {
          uni.showToast({ title: "未查询到供应商" });
        }
      }
    });
  }

  // 新增供应商卡号必填 编辑供应商卡号非必填
  if (!option.item) {
    formAttrList[1].required = true;
  }
  // 设置页面标题
  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>
