<template>
  <view class="c-card">
    <u-form
      labelPosition="left"
      :model="model1"
      :rules="rules"
      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 formAttrList"
        :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 formAttrList" :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="true"
  ></SupplierDialog>
</template>
<script setup lang="ts">
import { CustomerApi, FinanceApi, PictureApi } 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.customerName = obj.name;
  model1.order.customerId = obj.id;
};

// 金额
const handleInput = (e: any, item: any) => {
  if (
    ["totalPrice"].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 rules = reactive({
  "order.customerName": {
    type: "string",
    required: true,
    message: "请选择客户",
    trigger: ["blur", "change"],
  },
  "order.settlementTime": {
    type: "string",
    required: true,
    message: "请选择结算时间",
    trigger: ["blur", "change"],
  },
  "order.totalPrice": {
    type: "number",
    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 formAttrList = reactive<any>([
  {
    name: "客户",
    key: "customerName",
    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",
  },
]);
// 监听毛重 皮重
watch([() => model1.order.buttonType], ([buttonTypeNew]) => {
  if (buttonTypeNew === 3) {
    contrlModalParams.user.list = model1.supplierList;
  } else if (buttonTypeNew === 2) {
    contrlModalParams.user.list = model1.customerList;
  }
});

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.Income, // 收入明细
            });
          }
        })
        .catch((e) => {
          return;
        });
    });
  });
};
const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "user") {
    model1.order.customerName = v.name;
    model1.order.customerId = 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;
    contrlModalParams.user.list = 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 = 1; // 手动添加默认其他付款
  FinanceApi.addIncome(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>
