<template>
  <view class="c-card">
    <u-form
      labelPosition="left"
      :model="model1"
      :rules="rules"
      ref="form"
      :labelWidth="80"
      :labelStyle="{ padding: '0rpx 10rpx' }"
      :errorType="'border-bottom'"
    >
      <block v-for="(item, index) in formAttrList" :key="index">
        <!-- 自提的时候 隐藏运费和杂费 -->
        <u-form-item
          :prop="`order.${item.key}`"
          :label="item.name"
          :required="item.required"
          @click="item.fn"
          v-if="isShowFormItem(item)"
          :borderBottom="false"
        >
          <u-textarea
            v-if="item.type === 'textarea'"
            v-model="(model1.order as any)[(item.key as any)]"
            :placeholder="`请输入${item.name}`"
          ></u-textarea>
          <u-input
            v-if="item.type === 'select' || item.type === 'input'"
            v-model="(model1.order as any)[(item.key as any)]"
            :placeholder="`请${item.type === 'select' ? '选择' : '输入'}${
              item.name
            }`"
            clearable
            :customStyle="{}"
            border="none"
            :disabled="item.disabled || item.type === 'select'"
            :disabledColor="item.name === '结算方式' ? '#ffffff' : '#f5f7fa'"
            @change="(e:any) => {handleInput(e, item)}"
            @clear="handleClear(item)"
          >
            <template #suffix>
              <text v-if="item.key === 'subtractNum'">
                {{ model1.order.buttonType === 0 ? item.unit : "%" }}
              </text>
              <text v-else>
                {{ item.unit }}
              </text>
            </template>
          </u-input>
          <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
              v-for="(c, index) in item.child"
              :key="index"
              activeColor="#00DCEE"
              :label="c.name"
              :name="c.id"
              :customStyle="{ marginRight: '10px' }"
            ></u-radio>
          </u-radio-group>

          <template #right v-if="item.type === 'select'">
            <u-icon name="arrow-right"></u-icon>
          </template>
        </u-form-item>
      </block>
    </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>
</template>
<script setup lang="ts">
import { PictureApi, ShipmentApi } from "@/services";
import type { ComType } from "@/types/global";
import { formatDate } from "@/utils";
import {
  ImagesType,
  OrderType,
  ScaleStatus,
  ScaleStatusBtnType,
} from "@/utils/enum";
import valid from "@/utils/validate";
import { onLoad } from "@dcloudio/uni-app";
const handleClear = (item:any) => {
  (model1.order as any)[item.key] = '';
}
const isShowFormItem = (item: any) => {
  if (model1.scaleStatusBtnType === ScaleStatusBtnType.ShipmentPay) {
    return true;
  } else {
    return (
      item.key !== "paymentMethodName" &&
      !(
        model1.order.deliveryMethod === 1 &&
        ["freight", "incidentals"].indexOf(item.key) > -1
      )
    );
  }
};
// 毛重 皮重 过磅净重 结算单价 结算重量 预估总价 结算金额校验
const handleInput = (e: any, item: any) => {
  if (
    [
      "settlementGross",
      "settlementTare",
      "settlementNet",
      "unitPrice",
      "settlementWeight",
      "estimatePrice",
      "totalPrice",
      "freight",
      "incidentals",
      "subtractNum",
    ].indexOf(item.key) > -1
  ) {
    const temp = e?.replace(valid.valid_decimal.pattern, "");
    if (item.key === "subtractNum") {
      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;
    }, 10);
  }
};
const model1 = reactive<{
  scaleStatusBtnType: number;
  order: Shipment;
}>({
  scaleStatusBtnType: 2,
  order: {
    id: "",
    splTime: "",
    takeType: 1,
    fileLists: [],
    buttonType: 0,
    deliveryMethod: 0,
    settlementGross: 0,
    settlementTare: 0,
    settlementWeight: 0,
    unitPrice: 0,
    estimatePrice: 0,
    subtractNum: 0,
  },
});
const rules = reactive({
  "order.settlementGross": {
    type: "number",
    required: true,
    message: "结算毛重为空或输入错误",
    trigger: ["blur", "change"],
  },
  "order.settlementTare": {
    type: "number",
    required: true,
    message: "结算皮重为空或输入错误",
    trigger: ["blur", "change"],
  },
  "order.settlementNet": {
    type: "number",
    required: true,
    message: "过磅净重为空或输入错误",
    trigger: ["blur", "change"],
  },
  "order.unitPrice": {
    type: "number",
    required: true,
    message: "结算单价为空或输入错误",
    trigger: ["blur", "change"],
  },
  "order.settlementWeight": {
    type: "number",
    required: true,
    message: "结算重量为空或输入错误",
    trigger: ["blur", "change"],
  },
  "order.estimatePrice": {
    type: "number",
    required: true,
    message: "预估总价为空或输入错误",
    trigger: ["blur", "change"],
  },
  "order.totalPrice": {
    type: "number",
    required: true,
    message: "结算金额为空或输入错误",
    trigger: ["blur", "change"],
  },
});
const contrlModalParams = reactive<ComType>({
  select: {
    isShow: false,
    title: "标题",
    list: [
      {
        name: "微信",
        key: 3,
      },
      {
        name: "现金",
        key: 1,
      },
      {
        name: "支付宝",
        key: 4,
      },
      {
        name: "转账",
        key: 2,
      },
    ],
  },
});

const formAttrList = reactive<ComType>([
  {
    name: "毛重",
    key: "settlementGross",
    type: "input",
    required: true,
    unit: "kg",
    fn: () => {},
    isNumber: true,
  },
  {
    name: "皮重",
    key: "settlementTare",
    type: "input",
    required: true,
    unit: "kg",
    fn: () => {},
    isNumber: true,
  },
  {
    name: "过磅净重",
    key: "settlementNet",
    type: "input",
    required: true,
    disabled: true,
    unit: "kg",
    fn: () => {},
    isNumber: true,
  },
  {
    name: "结算单价",
    key: "unitPrice",
    type: "input",
    required: true,
    unit: "元/kg",
    fn: () => {},
    isNumber: true,
  },
  // {
  //   name: "验货净重",
  //   key: "number",
  //   type: "input",
  //   required: true,
  //   unit: "件",
  // },
  {
    name: "扣杂",
    key: "buttonType",
    type: "radio",
    child: [
      {
        id: 0,
        name: "按固定重量",
      },
      {
        id: 1,
        name: "按百分比",
      },
    ],
  },
  {
    name: "杂质扣除",
    key: "subtractNum",
    type: "input",
    unit: "KG",
    isNumber: true,
  },
  {
    name: "结算重量",
    key: "settlementWeight",
    type: "input",
    required: true,
    disabled: true,
    unit: "KG",
    isNumber: true,
  },
  {
    name: "预估总价",
    key: "estimatePrice",
    required: true,
    disabled: true,
    type: "input",
    unit: "元",
    isNumber: true,
  },
  {
    name: "结算金额",
    key: "totalPrice",
    required: true,
    type: "input",
    unit: "元",
    isNumber: true,
  },
  {
    name: "提货方式",
    key: "deliveryMethodName",
    type: "input",
    unit: "",
    disabled: true,
    // child: [
    //   {
    //     id: 0,
    //     name: "送货",
    //   },
    //   {
    //     id: 1,
    //     name: "自提",
    //   },
    // ],
  },
  {
    name: "运费",
    key: "freight",
    type: "input",
    unit: "元",
    isNumber: true,
  },
  {
    name: "杂费",
    key: "incidentals",
    type: "input",
    unit: "元",
    isNumber: true,
  },
  {
    name: "实际收入",
    key: "realIncome",
    type: "input",
    unit: "元",
    disabled: true,
    isNumber: true,
  },
  {
    name: "结算方式",
    key: "paymentMethodName",
    required: true,
    type: "select",
    unit: "",
    childKey: "select",
    fn: () => {
      contrlModalParams.select.isShow = true;
      contrlModalParams.select.title = "结算方式";
    },
  },
  {
    name: "备注",
    key: "settlementNotes",
    type: "textarea",
  },
  {
    name: "结算单据",
    key: "photo",
    type: "upload",
  },
]);

// const handleIsShowInput = (item: any) => {
//   if () {
//     return true
//   } else {
//     if (model1.order.deliveryMethod === 0 && ['freight', 'incidentals'].indexOf(item.key) > -1) {
//       return false
//     } {
//       return true
//     }
//   }

// }

// 监听毛重 皮重
watch(
  [
    () => model1.order.settlementGross,
    () => model1.order.settlementTare,
    () => model1.order.unitPrice,
    () => model1.order.subtractNum,
    () => model1.order.buttonType,
    () => model1.order.freight,
    () => model1.order.incidentals,
    () => model1.order.totalPrice,
    () => model1.order.deliveryMethod,
  ],
  ([settlementGrossNew, settlementTareNew]) => {
    // 自提清空运费和杂费
    if (model1.order.deliveryMethod === 1) {
      model1.order.freight = 0;
      model1.order.incidentals = 0;
    }
    /**
     * 过磅净重： 毛重-皮重
      结算重量： 过磅净重-扣杂
      预估总价： 结算单价*结算重量
      实际收入：实际结算金额-运费-杂费
     */
    model1.order.settlementNet =
      (settlementGrossNew || 0) - (settlementTareNew || 0);
    if (model1.order.buttonType === 0) {
      if (model1.order.subtractNum) {
        model1.order.settlementWeight =
          model1.order.settlementNet - model1.order.subtractNum;
      } else {
        model1.order.settlementWeight = model1.order.settlementNet;
      }
    } else if (model1.order.buttonType === 1) {
      if (model1.order.subtractNum) {
        model1.order.settlementWeight =
          model1.order.settlementNet * ((100 - model1.order.subtractNum) / 100);
      } else {
        model1.order.settlementWeight = model1.order.settlementNet;
      }
    }
    model1.order.estimatePrice = parseInt(
      (
        (model1.order.unitPrice || 0) * (model1.order.settlementWeight || 0)
      ).toFixed(2)
    );
    if (!model1.order.totalPrice) {
      model1.order.totalPrice = model1.order.estimatePrice;
    }

    model1.order.realIncome =
      (model1.order.totalPrice || 0) -
      (model1.order.freight || 0) -
      (model1.order.incidentals || 0);
  }
);

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.Shipment, // 出库单
            });
          }
        })
        .catch((e) => {
          return;
        });
    });
  });
};

const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "select") {
    model1.order.paymentMethodName = v.name;
    model1.order.paymentMethod = v.key;
  }
};
const handleDelete = (e: any) => {
  if (e.tempFile.fileID) {
    PictureApi.deleteById({ id: e.tempFile.fileID }).then((res) => {
      if (res.code === 200) {
        uni.showToast({ title: "已删除" });
      }
    });
  }
};
/**
 * 校验
 */
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 || "校验失败",
        });
      });
  });
};
/**
 * 点击保存 先执行upload接口
 * 上传成功后 保存图片资源 和更新订单数据
 */
const save = () => {
  for (let i = 0; i < formAttrList.length; i++) {
    if (formAttrList[i].isNumber) {
      if (
        model1.order[formAttrList[i].key] &&
        model1.order[formAttrList[i].key][
          model1.order[formAttrList[i].key].length - 1
        ] === "."
      ) {
        uni.showToast({
          title: "请输入正确的" + formAttrList[i].name,
          icon: "none",
        });
        return;
      }
    }
  }

  check().then((res) => {
    if (res) {
      startSave();
    }
  });
};

const startSave = () => {
  Promise.all(handleUpload()).then((res) => {
    // 上传多个资源
    if (res.length > 0) {
      PictureApi.addListAnnex({ annexPos: res }).then((res1) => {
        if (res1.code === 200) {
          console.log("*** 资源文件更新成功");
        }
      });
    }
  });
  updateOrder();
};

const updateOrder = () => {
  // 根据不同按钮点击到form 状态不同
  let scaleStatus = ref(0);
  if (model1.scaleStatusBtnType === ScaleStatusBtnType.ShipmentNoPay) {
    scaleStatus.value = ScaleStatus.ToBeShipmentPay;
  }
  if (model1.scaleStatusBtnType === ScaleStatusBtnType.ShipmentPay) {
    scaleStatus.value = ScaleStatus.ShipmentPaid;
  }
  /**
   * buttonType
   * 0扣杂1扣点
   * buttonType===0 buckleMiscellaneous
   * buttonType===1 points
   *
   */
  if (model1.order.buttonType === 0) {
    model1.order.buckleMiscellaneous = model1.order.subtractNum;
  } else if (model1.order.buttonType === 1) {
    model1.order.points = model1.order.subtractNum;
  }
  model1.order.signTime = formatDate(new Date(), "{y}-{m}-{d} {h}:{i}:{s}");
  // 更新出货单
  ShipmentApi.updateOrderIn({
    orderOutPos: [{ ...model1.order, scaleStatus: scaleStatus.value }],
  }).then((res) => {
    if (res.code === 200) {
      uni.showToast({
        title: "编辑成功",
        icon: "success",
      });

      uni.navigateBack({
        delta: 1,
        success: (res) => {
          uni.$emit("shipmentReviewUrlParams", {
            id: model1.order.id,
            scaleStatusBtnType: model1.scaleStatusBtnType,
          });
        },
      });
    }
  });
};

onLoad((option) => {
  model1.order.id = (option as any).id;
  model1.scaleStatusBtnType = parseInt((option as any).scaleStatusBtnType);
  if (model1.order.id) {
    ShipmentApi.getDetailById({ id: model1.order.id }).then((res) => {
      if (res.code === 200) {
        model1.order = {
          ...res.data,
          buttonType: res.data.buttonType !== null ? res.data.buttonType : 0,
          deliveryMethod:
            res.data.deliveryMethod !== null ? res.data.deliveryMethod : 0,
          subtractNum:
            res.data.buttonType === 0
              ? res.data.buckleMiscellaneous
              : res.data.points,
          deliveryMethodName: res.data.deliveryMethod === 0 ? "送货" : "自提",
          fileLists: model1.order.fileLists.map((item: any) => {
            return { ...item, fileID: item.id };
          }),
        };
      }
    });

    PictureApi.getAnnex({
      businessId: model1.order.id,
      orderType: OrderType.Shipment,
      imagesType: ImagesType.NORMARL,
    }).then((res) => {
      if (res.code === 200) {
        model1.order.fileLists = res.data;
      }
    });
  }
});
</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>
