<template>
  <view class="c-card">
    <u-form
      labelPosition="left"
      :model="model1"
      :rules="rules"
      ref="form"
      :labelWidth="80"
      :labelStyle="{ padding: '0rpx 10rpx' }"
    >
      <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="item.key !== 'paymentMethodName'"
        >
          <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="true"
            :customStyle="{}"
            border="none"
          >
            <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.fileList"
            limit="10"
            title="最多可上传10张图片"
            :auto-upload="false"
            fileMediatype="image"
            mode="grid"
            ref="filesShipmentRef"
          ></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>
        <!-- 控制结算方式是否显示 -->
        <u-form-item
          :prop="`order[${item.key}]`"
          :label="item.name"
          :required="item.required"
          @click="item.fn"
          v-if="
            item.key === 'paymentMethodName' &&
            model1.scaleStatusBtnType === ScaleStatusBtnType.ShipmentPay
          "
        >
          <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="true"
            :customStyle="{}"
            border="none"
          >
            <template #suffix>
              <text v-if="item.key === 'subtractNum'">
                {{ model1.order.buttonType === 0 ? item.unit : "%" }}
              </text>
              <text v-else>
                {{ item.unit }}
              </text>
            </template>
          </u-input>
          <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 { onLoad } from "@dcloudio/uni-app";
const model1 = reactive<{
  scaleStatusBtnType: number,
  order: Shipment
}>({
  scaleStatusBtnType: 2,
  order: {
    id: '',
    splTime: "",
    takeType: 1,
    fileList: [],
    buttonType: 0,
  },
});
const rules = ref({
  "userInfo.userName": {
    type: "string",
    required: true,
    message: "请输入手机号",
    trigger: ["blur", "change"],
  },
  "userInfo.password": {
    type: "string",
    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: () => {},
  },
  {
    name: "皮重",
    key: "settlementTare",
    type: "input",
    required: true,
    unit: "kg",
    fn: () => {},
  },
  {
    name: "过磅净重",
    key: "settlementNet",
    type: "input",
    required: true,
    unit: "kg",
    fn: () => {},
  },
  {
    name: "结算单价",
    key: "unitPrice",
    type: "input",
    required: true,
    unit: "元/kg",
    fn: () => {},
  },
  // {
  //   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",
  },
  {
    name: "结算重量",
    key: "settlementWeight",
    type: "input",
    required: true,
    unit: "KG",
  },
  {
    name: "预估总价",
    key: "estimatePrice",
    required: true,
    type: "input",
    unit: "元",
  },
  {
    name: "结算金额",
    key: "totalPrice",
    required: true,
    type: "input",
    unit: "元",
  },
  {
    name: "提货方式",
    key: "deliveryMethod",
    type: "radio",
    unit: "",
    child: [
      {
        id: 0,
        name: "送货",
      },
      {
        id: 1,
        name: "自提",
      },
    ],
  },
  {
    name: "运费",
    key: "freight",
    type: "input",
    unit: "元",
  },
  {
    name: "杂费",
    key: "incidentals",
    type: "input",
    unit: "元",
  },
  {
    name: "实际收入",
    key: "realIncome",
    type: "input",
    unit: "元",
  },
  {
    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 filesShipmentRef = ref();
const handleUpload = () => {
  // console.log(event.tempFilePaths)
  const list = filesShipmentRef.value[0].filesList;
  return list.map((item: any) => {
    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.Settlement, // 单据资源
            orderType: OrderType.Shipment, // 出库单
          });
        }
      });
    });
  });
};

const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "select") {
    model1.order.paymentMethodName = v.name;
    model1.order.paymentMethod = v.id;
  }
};

/**
 * 点击保存 先执行upload接口
 * 上传成功后 保存图片资源 和更新订单数据
 */
const save = () => {
  Promise.all(handleUpload()).then((res) => {
    // 上传多个资源
    if (res.length > 0) {
      PictureApi.addListAnnex({ annexPos: res }).then((res1) => {
        if (res1.code === 200) {
          uni.showToast({
            title: "图片资源上传成功",
            icon: "success",
          });
        }
      });
    }
  });

  // 根据不同按钮点击到form 状态不同
  let scaleStatus = ref(0);
  if (model1.scaleStatusBtnType === ScaleStatusBtnType.ShipmentNoPay) {
    scaleStatus.value = ScaleStatus.ToBeShipmentPay;
  }
  if (model1.scaleStatusBtnType === ScaleStatusBtnType.ShipmentPay) {
    scaleStatus.value = ScaleStatus.ShipmentPaid;
  }
  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.navigateTo({
        url:
          "/pagesShipment/review/index?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 };
        console.log(model1.order);
      }
    });

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