<template>
  <view class="c-card">
    <u-form
      labelPosition="left"
      :model="model1"
      :rules="model1.order.buttonType === 3 ? rules1 : rules2"
      ref="form"
      :labelWidth="80"
      :labelStyle="{ padding: '0rpx 10rpx' }"
      :errorType="'border-bottom'"
    >
      <u-form-item
        :prop="`order.${item.key}`"
        :label="item.name"
        :required="item.required"
        v-for="(item, index) in model1.order.buttonType === 3
          ? formAttrList1
          : formAttrList2"
        :key="index"
        @click="item.fn"
      >
        <u-textarea
          v-if="item.type === 'textarea'"
          v-model="(model1.order as any)[item.key]"
          :placeholder="`请输入${item.name}`"
        ></u-textarea>
        <u-input
          v-if="item.type === 'select' || item.type === 'input'"
          v-model="(model1.order as any)[item.key]"
          :placeholder="`请${item.type === 'select' ? '选择' : '输入'}${
            item.name
          }`"
          clearable
          :customStyle="{}"
          border="none"
          :disabled="item.disabled || item.type === 'select'"
          :disabledColor="['供应商','客户','结算时间', '结算方式'].indexOf(item.name) > -1?'#ffffff':'#f5f7fa'"
          @change="(e:any) => {handleInput(e, item)}"
          @clear="handleClear(item)"
        >
          <template #suffix>
            <text>
              {{ item.unit }}
            </text>
          </template>
        </u-input>
        <!-- @afterRead="afterRead"
          @delete="deletePic" -->
        <uni-file-picker
          v-if="item.type === 'upload'"
          v-model="model1.order.fileLists"
          limit="9"
          title="最多可上传9张图片"
          :auto-upload="false"
          fileMediatype="image"
          mode="grid"
          ref="filesRef"
          @delete="handleDelete"
        ></uni-file-picker>
        <u-radio-group
          v-if="item.type === 'radio'"
          v-model="(model1.order as any)[item.key]"
          placement="row"
        >
          <u-radio activeColor="#00DCEE" label="供应商" :name="3"></u-radio>
          &nbsp;&nbsp;&nbsp;
          <u-radio activeColor="#00DCEE" label="客户" :name="2"></u-radio>
        </u-radio-group>
        <template #right v-if="item.type === 'select'">
          <u-icon name="arrow-right"></u-icon>
        </template>
      </u-form-item>
    </u-form>
    <u-datetime-picker
      :show="contrlModalParams.isShowSplTime"
      v-model="contrlModalParams.settlementTime"
      mode="datetime"
      @confirm="(v: any) => {handleTime(v)}"
      @cancel="contrlModalParams.isShowSplTime = false"
      :closeOnClickOverlay="true"
    ></u-datetime-picker>
    <block
      v-for="(item, index) in model1.order.buttonType === 3
        ? formAttrList1
        : formAttrList2"
      :key="index"
    >
      <u-action-sheet
        v-if="item.type === 'select' && item.key !== 'settlementTime'"
        :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>

  <!-- 供应商选择弹框 -->
  <SupplierDialog
    ref="supplierDialog"
    :show="showDialog.showSupplier"
    @handleDialog="(v:boolean) => {handleDialog('showSupplier', v)}"
    @changeUser="changeUser"
    :isShipment="model1.order.buttonType === 2"
  ></SupplierDialog>
</template>
<script setup lang="ts">
import { CustomerApi, FinanceApi, PictureApi, SupplierApi } from "@/services";
import { countDots, formatDate } from "@/utils";
import { ImagesType, OrderType } from "@/utils/enum";
import _ from "underscore";
import SupplierDialog from "./SupplierDialog.vue";
import valid from "@/utils/validate";
const handleClear = (item:any) => {
  (model1.order as any)[item.key] = '';
}
// 供应商选择
const showDialog = <
  {
    [key: string]: boolean;
  }
>reactive({
  showSupplier: false,
  showProduct: false,
});

const handleDialog = (key: string, v: boolean) => {
  showDialog[key] = v;
};

const changeUser = (obj: any) => {
  model1.order.supCusName = obj.name;
  model1.order.supCusId = obj.id;
};

// 供应商（金额） 客户（杂费 运费）校验
const handleInput = (e: any, item: any) => {
  if (
    ["totalPrice", "incidentals", "freight"].indexOf(item.key) > -1
  ) {
    const temp = e?.replace(valid.valid_decimal.pattern, "");
    if (countDots(temp).length > 1) {
      uni.showToast({
        title: "请输入正确的" + item.name,
        icon: "none",
      });
    }

    setTimeout(() => {
      model1.order[item.key] = temp;
    }, 10);
  }
};

const model1 = reactive<any>({
  order: {
    buttonType: 3,
    fileLists: [],
    settlementTime: "",
  },
  supplierList: [],
  customerList: [],
});
const rules1 = reactive({
  "order.supCusName": {
    type: "string",
    required: true,
    message: "请选择供应商",
    trigger: ["blur", "change"],
  },
  "order.settlementTime": {
    type: "string",
    required: true,
    message: "请选择结算时间",
    trigger: ["blur", "change"],
  },
  "order.totalPrice": {
    type: "string",
    required: true,
    message: "请输入金额",
    trigger: ["blur", "change"],
  },
  "order.paymentMethodName": {
    type: "string",
    required: true,
    message: "请选择结算方式",
    trigger: ["blur", "change"],
  },
});
const rules2 = reactive({
  "order.supCusName": {
    type: "string",
    required: true,
    message: "请选择客户",
    trigger: ["blur", "change"],
  },
  "order.settlementTime": {
    type: "string",
    required: true,
    message: "请选择结算时间",
    trigger: ["blur", "change"],
  },
  "order.incidentals": {
    type: "string",
    required: true,
    message: "请输入杂费",
    trigger: ["blur", "change"],
  },
  "order.freight": {
    type: "string",
    required: true,
    message: "请输入运费",
    trigger: ["blur", "change"],
  },
  "order.paymentMethodName": {
    type: "string",
    required: true,
    message: "请选择结算方式",
    trigger: ["blur", "change"],
  },
});
const contrlModalParams = reactive<any>({
  isShowSplTime: false,
  settlementTime: Number(new Date()),
  user: {
    isShow: false,
    title: "标题",
    list: [],
  },
  paySelect: {
    isShow: false,
    title: "标题",
    list: [
      {
        name: "微信",
        id: 3,
      },
      {
        name: "现金",
        id: 1,
      },
      {
        name: "支付宝",
        id: 4,
      },
      {
        name: "转账",
        id: 2,
      },
    ],
  },
});

const formAttrList1 = reactive<any>([
  {
    name: "付款类型",
    key: "buttonType",
    required: true,
    type: "radio",
  },
  {
    name: "供应商",
    key: "supCusName",
    type: "select",
    childKey: "user",
    required: true,
    unit: "",
    fn: () => {
      // contrlModalParams.user.isShow = true;
      // contrlModalParams.user.title = "供应商";
      handleDialog("showSupplier", true);
      uni.hideKeyboard();
    },
  },
  {
    name: "结算时间",
    key: "settlementTime",
    type: "select",
    unit: "",
    required: true,
    fn: () => {
      contrlModalParams.isShowSplTime = true;
    },
  },
  {
    name: "金额",
    key: "totalPrice",
    type: "input",
    required: true,
    unit: "元",
  },
  {
    name: "结算方式",
    key: "paymentMethodName",
    type: "select",
    childKey: "paySelect",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams.paySelect.isShow = true;
      contrlModalParams.paySelect.title = "结算方式";
    },
  },
  {
    name: "备注",
    key: "remakes",
    type: "textarea",
  },
  {
    name: "支付单据",
    key: "photo",
    type: "upload",
  },
]);

const formAttrList2 = reactive<any>([
  {
    name: "付款类型",
    key: "buttonType",
    required: true,
    type: "radio",
  },
  {
    name: "客户",
    key: "supCusName",
    type: "select",
    childKey: "user",
    required: true,
    unit: "",
    fn: () => {
      // contrlModalParams.user.isShow = true;
      // contrlModalParams.user.title = "客户";
      handleDialog("showSupplier", true);
      uni.hideKeyboard();
    },
  },
  {
    name: "结算时间",
    key: "settlementTime",
    type: "select",
    unit: "",
    required: true,
    fn: () => {
      contrlModalParams.isShowSplTime = true;
    },
  },
  {
    name: "杂费",
    key: "incidentals",
    type: "input",
    required: true,
    unit: "元",
  },
  {
    name: "运费",
    key: "freight",
    type: "input",
    required: true,
    unit: "元",
  },
  {
    name: "结算方式",
    key: "paymentMethodName",
    type: "select",
    childKey: "paySelect",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams.paySelect.isShow = true;
      contrlModalParams.paySelect.title = "结算方式";
    },
  },
  {
    name: "备注",
    key: "remakes",
    type: "textarea",
  },
  {
    name: "支付单据",
    key: "photo",
    type: "upload",
  },
]);
// 监听付款类型
watch([() => model1.order.buttonType], ([buttonTypeNew]) => {
  if (buttonTypeNew === 3) {
    contrlModalParams.user.list = model1.supplierList;
    model1.order.paymentMethodName = "";
    model1.order.paymentMethod = "";
  } else if (buttonTypeNew === 2) {
    contrlModalParams.user.list = model1.customerList;
    model1.order.supCusName = "";
    model1.order.supCusId = "";
  }
});

const handleDelete = (e: any) => {
  console.log(model1.order.fileLists);
  if (e.tempFile.fileID) {
    PictureApi.deleteById({ id: e.tempFile.fileID }).then((res) => {
      if (res.code === 200) {
        uni.showToast({ title: "已删除" });
      }
    });
  }
};

const filesRef = ref();
const handleUpload = () => {
  // console.log(event.tempFilePaths)
  return filesRef.value[0].filesList.map((item: any, index: number) => {
    if (item.fileID) {
      return;
    }
    return new Promise((resolve) => {
      PictureApi.upload({
        files: item,
        path: item.path,
      })
        .then((res) => {
          if (res.code === 200) {
            resolve({
              ...(res.data as any),
              businessId: model1.order.id,
              imagesType: ImagesType.NORMARL, // 普通资源
              orderType: OrderType.Pay, // 收入明细
            });
          }
        })
        .catch((e) => {
          return;
        });
    });
  });
};
const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "user") {
    model1.order.supCusName = v.name;
    model1.order.supCusId = v.id;
  } else if (key === "paySelect") {
    model1.order.paymentMethodName = v.name;
    model1.order.paymentMethod = v.id;
  }
};
// 供应商信息
SupplierApi.getSupplierUserList({}).then((res) => {
  if (res.code === 200) {
    model1.supplierList = res.data;
    contrlModalParams.user.list = res.data;
  }
});
// 客户信息
CustomerApi.getCustomUserList({}).then((res) => {
  if (res.code === 200) {
    model1.customerList = res.data;
  }
});
const upload = () => {
  Promise.all(handleUpload()).then((res) => {
    // 上传多个资源
    if (res.length > 0) {
      PictureApi.addListAnnex({ annexPos: res }).then((res1) => {
        if (res1.code === 200) {
          console.log("*** 资源文件更新成功");
        }
      });
    }
  });
};

/**
 * 校验
 */
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 = () => {
  check().then((res) => {
    if (res) {
      startSave();
    }
  });
};

const startSave = () => {
  model1.order.paymentType = model1.order.buttonType;
  if (model1.order.buttonType === 2) {
    model1.order.totalPrice =
      parseInt(model1.order.freight) + parseInt(model1.order.incidentals);
  }
  FinanceApi.addPaymentDetails(model1.order).then((res) => {
    if (res.code === 200) {
      model1.order.id = res.data;
      upload();
      uni.navigateBack()
    }
  });
};
const handleTime = (v: any) => {
  model1.order.settlementTime = formatDate(v.value, "{y}-{m}-{d} {h}:{i}:{s}");
  contrlModalParams.isShowSplTime = false;
};
</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>
