<template>
  <view class="c-card">
    <u-form
      labelPosition="left"
      :model="model1"
      :rules="rules"
      ref="form"
      :labelWidth="80"
      :labelStyle="{ padding: '0rpx 10rpx' }"
    >
      <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="true"
          :customStyle="{}"
          border="none"
        >
          <template #suffix>
            <text v-if="item.key === 'subtractNum'">
              {{ model1.order.buttonType === 1 ? item.unit : "%" }}
            </text>
            <text v-else>
              {{ item.unit }}
            </text>
          </template>
        </u-input>
        <!-- @afterRead="afterRead"
          @delete="deletePic" -->
        <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="filesRef"
        ></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="1"></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.spltime"
      mode="datetime"
      @confirm="(v: any) => {handleTime(v)}"
      @cancel="contrlModalParams.isShowSplTime = false"
    ></u-datetime-picker>
    <block v-for="(item, index) in formAttrList" :key="index">
      <u-action-sheet
        v-if="item.type === 'select' && item.key !== 'repairTime'"
        :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 {
  DeviceApi,
  PictureApi,
  ProfileApi,
  ReceiveApi,
  ReceiveProductApi,
} from "@/services";
import { formatDate } from "@/utils";
import { DeviceType, ImagesType, OrderType } from "@/utils/enum";
import _ from "underscore";

const model1 = reactive<any>({
  order: {
    buttonType: 0,
    fileList: [],
    splTime: "",
    subtractType: 1,
  },
});
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<any>({
  isShowSplTime: false,
  spltime: "",
  device: {
    isShow: false,
    title: "标题",
    list: [],
  },
  user: {
    isShow: false,
    title: "标题",
    list: [],
  },
  product: {
    isShow: false,
    title: "标题",
    list: [],
  },
});

const formAttrList = reactive<any>([
  {
    name: "补单时间",
    key: "repairTime",
    type: "select",
    unit: "",
    required: true,
    fn: () => {
      contrlModalParams.isShowSplTime = true;
    },
  },
  {
    name: "站点磅秤",
    key: "deviceName",
    type: "select",
    childKey: "device",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams.device.isShow = true;
      contrlModalParams.device.title = "站点磅秤";
    },
  },
  {
    name: "供应商",
    key: "userName",
    type: "select",
    childKey: "user",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams.user.isShow = true;
      contrlModalParams.user.title = "供应商";
    },
  },
  {
    name: "车牌号",
    key: "carNumber",
    type: "input",
    unit: "",
  },
  {
    name: "收货产品",
    key: "productName",
    type: "select",
    childKey: "product",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams.product.isShow = true;
      contrlModalParams.product.title = "收货产品";
    },
  },
  {
    name: "毛重",
    key: "grossWeight",
    type: "input",
    required: true,
    unit: "KG",
  },
  {
    name: "皮重",
    key: "tare",
    type: "input",
    required: true,
    unit: "KG",
  },
  {
    name: "扣杂",
    key: "buttonType",
    type: "radio",
  },
  {
    name: "杂质扣除",
    key: "subtractNum",
    type: "input",
    unit: "KG",
  },
  {
    name: "净重",
    key: "netWeight",
    type: "input",
    unit: "KG",
  },
  {
    name: "单价",
    key: "price",
    type: "input",
    required: true,
    unit: "元/KG",
  },
  {
    name: "预估总价",
    key: "totalPrice",
    type: "input",
    unit: "元",
  },
  {
    name: "贷款金额",
    key: "balanceTotalPrice",
    type: "input",
    required: true,
    unit: "元",
  },
  {
    name: "备注",
    key: "notes",
    type: "textarea",
  },
  {
    name: "货品照片",
    key: "photo",
    type: "upload",
  },
]);
const filesRef = ref();
const handleUpload = () => {
  // console.log(event.tempFilePaths)
  const list = filesRef.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 as any).id,
            imagesType: ImagesType.NORMARL, // 普通资源
            orderType: OrderType.Receive, // 入库单
          });
        }
      });
    });
  });
};
const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "user") {
    debugger;
    model1.order.userName = v.name;
    model1.order.userId = v.id;
  } else if (key === "product") {
    model1.order.productName = v.name;
    model1.order.productId = v.id;
  } else if (key === "device") {
    model1.order.deviceName = v.name;
    model1.order.deviceId = v.id;
  }
};
// 供应商信息
ProfileApi.getUserList({ userType: 2 }).then((res) => {
  if (res.code === 200) {
    contrlModalParams.user.list = res.data;
    console.log(contrlModalParams.user.list);
  }
});
// 产品信息
ReceiveProductApi.getAllReProducts().then((res) => {
  if (res.code === 200) {
    contrlModalParams.product.list = _.map(
      res.data as any,
      function (item: any) {
        return { name: item.reProductsName, ...item };
      }
    );
  }
});
// 设备信息
DeviceApi.getDeviceList({ deviceType: DeviceType.Weighbridge }).then((res) => {
  if (res.code === 200) {
    contrlModalParams.device.list = _.map(
      res.data as any,
      function (item: any) {
        return { name: item.deviceName, ...item };
      }
    );
  }
});
const upload = () => {
  Promise.all(handleUpload()).then((res) => {
    // 上传多个资源
    if (res.length > 0) {
      PictureApi.addListAnnex({ annexPos: res }).then((res1) => {
        if (res1.code === 200) {
          uni.showToast({
            title: "图片资源上传成功",
            icon: "success",
          });
        }
      });
    }
  });
};
const save = () => {
  if (model1.order.buttonType === 0) {
    model1.order.buckleMiscellaneous = model1.order.subtractNum;
  } else if (model1.order.buttonType === 1) {
    model1.order.points = model1.order.subtractNum;
  }
  ReceiveApi.addOrderIn(model1.order).then((res) => {
    if (res.code === 200) {
      model1.order.id = res.data;
      upload();
      uni.navigateTo({
        url: "/pages/index/index", // 要跳转到的页面路径
      });
    }
  });
};
const handleTime = (v: any) => {
  model1.order.repairTime = 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>
