<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"
        :borderBottom="false"
      >
        <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 === 0 ? item.unit : "%" }}
            </text>
            <text v-else>
              {{ item.unit }}
            </text>
          </template>
        </u-input>
        <!-- @afterRead="afterRead"
          @delete="deletePic" -->
        <uni-file-picker
          v-if="item.type === 'upload'"
          :limit="10"
          title="最多可上传10张图片"
          :auto-upload="false"
          fileMediatype="image"
          ref="filesRef"
          v-model="model1.order.fileLists"
          @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>
    </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 text="暂不定价" @click="handleBack()"></u-button>
    <u-button type="primary" text="保存" @click="save()"></u-button>
  </view>
</template>
<script setup lang="ts">
import type { ComType } from "@/types/global";
import {
  ProfileApi,
  ReceiveProductApi,
  ReceiveApi,
  PictureApi,
} from "@/services/index";
import _ from "underscore";
import { onLoad } from "@dcloudio/uni-app";
import { ImagesType, OrderType } from "@/utils/enum";
const model1 = reactive<{ order: Order }>({
  order: {
    id: 0,
    userName: "", // 供应商名称
    userId: "", // 供应商Id,
    carNumber: "",
    productId: "", // 产品Id,
    productName: "", // 产品名称
    price: "", // 单价
    buttonType: 0, // 0扣杂1扣点
    weighingMethod: 0, // 0：有皮重 1：零皮重
    multiCategory: 0, // 0：单品类 1：多品类
    fileLists: [],
    scaleStatus: 1,
  },
});
const rules = reactive({
  "order.userName": {
    type: "string",
    required: true,
    message: "请输入选择供应商",
    trigger: ["blur", "change"],
  },
  "order.productName": {
    type: "string",
    required: true,
    message: "请选择收货产品名称",
    trigger: ["blur", "change"],
  },
  "order.price": {
    type: "number",
    required: true,
    message: "请输入单价",
    trigger: ["blur", "change"],
  },
  "order.grossWeight": {
    type: "number",
    required: true,
    message: "请输入毛重",
    trigger: ["blur", "change"],
  },
  "order.weighingMethod": {
    type: "number",
    required: true,
    message: "请选择称重方式",
    trigger: ["blur", "change"],
  },
  "order.multiCategory": {
    type: "number",
    required: true,
    message: "请选择品类",
    trigger: ["blur", "change"],
  },
});
const contrlModalParams = reactive<ComType>({
  isShowSplTime: false,
  spltime: "",
  userSelect: {
    isShow: false,
    title: "标题",
    list: [],
  },
  productSelect: {
    isShow: false,
    title: "标题",
    list: [],
  },
});

const formAttrList = reactive<ComType>([
  {
    name: "供应商",
    key: "userName",
    type: "select",
    unit: "",
    childKey: "userSelect",
    required: true,
    fn: () => {
      contrlModalParams.userSelect.isShow = true;
      contrlModalParams.userSelect.title = "供应商";
    },
  },
  {
    name: "车牌号",
    key: "carNumber",
    type: "input",
    unit: "",
  },
  {
    name: "收货产品",
    key: "productName",
    type: "select",
    unit: "",
    childKey: "productSelect",
    required: true,
    fn: () => {
      contrlModalParams.productSelect.isShow = true;
      contrlModalParams.productSelect.title = "收货产品";
    },
  },
  {
    name: "单价",
    key: "price",
    type: "input",
    unit: "元/KG",
    required: true,
  },
  {
    name: "毛重",
    key: "grossWeight",
    type: "input",
    unit: "KG",
    required: true,
  },
  {
    name: "扣杂",
    key: "buttonType",
    type: "radio",
    child: [
      {
        id: 0,
        name: "按固定重量",
      },
      {
        id: 1,
        name: "按百分比",
      },
    ],
  },
  {
    name: "杂质扣除",
    key: "subtractNum",
    type: "input",
    unit: "KG",
  },
  {
    name: "称重方式",
    key: "weighingMethod",
    type: "radio",
    required: true,
    child: [
      {
        id: 0,
        name: "有皮重",
      },
      {
        id: 1,
        name: "零皮重",
      },
    ],
  },
  {
    name: "多品类",
    key: "multiCategory",
    type: "radio",
    required: true,
    child: [
      {
        id: 0,
        name: "单品类",
      },
      {
        id: 1,
        name: "多品类",
      },
    ],
  },

  {
    name: "备注",
    key: "notes",
    type: "textarea",
  },
  {
    name: "货品照片",
    key: "photo",
    type: "upload",
  },
]);

ProfileApi.getUserList({ userType: 2 }).then((res) => {
  if (res.code === 200) {
    contrlModalParams.userSelect.list = res.data;
  }
});
ReceiveProductApi.getAllReProducts().then((res) => {
  if (res.code === 200) {
    contrlModalParams.productSelect.list = _.map(
      res.data as any,
      function (item: any) {
        return { name: item.reProductsName, ...item };
      }
    );
  }
});
const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "userSelect") {
    model1.order.userName = v.name;
    model1.order.userId = v.id;
  } else if (key === "productSelect") {
    model1.order.productName = v.name;
    model1.order.productId = v.id;
  }
};

const handleBack = () => {
  uni.navigateBack();
};

// const files = ref<FileObj[]>([]);
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.Receive, // 入库单
            });
          }
        })
        .catch((e) => {
          return;
        });
    });
  });
};

/**
 *
 */
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: "已删除" });
      }
    });
  }
};

/**
 * 点击保存 先执行upload接口
 * 上传成功后 保存图片资源 和更新订单数据
 */
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 = () => {
  Promise.all(handleUpload()).then((res) => {
    if (res.filter((item) => item).length > 0) {
      PictureApi.addListAnnex({ annexPos: res.filter((item) => item) }).then(
        (res1) => {
          if (res1.code === 200) {
            updateOrder()
          }
        }
      );
    }
  });
};

const updateOrder = () => {
  // 更新定价单
  /**
   * 0：有皮重 1：零皮重
   * 有皮重 scaleState = 1 带过皮
     零皮重 scaleState = 2 带审核
   */
  if (model1.order.weighingMethod === 0) {
    model1.order.scaleStatus = 1;
  } else if (model1.order.weighingMethod === 1) {
    model1.order.scaleStatus = 2;
  }
  //
  /**
   * 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;
  }
  ReceiveApi.updateOne({ ...model1.order }).then((res) => {
    if (res.code === 200) {
      // 定价后 若是零皮-》跳转到【付款审核】  有皮重->【待过皮重】
      uni.showToast({
        title: "定价成功",
        icon: "success",
      });
      // 0：有皮重 1：零皮重
      uni.redirectTo({
        url: "/pagesHome/index", // 要跳转到的页面路径
      });
    }
  });
};

onLoad((option) => {
  model1.order.id = parseInt((option as any).id);
  if (model1.order.id) {
    ReceiveApi.getDetailById({ id: model1.order.id }).then((res) => {
      if (res.code === 200) {
        // 基于id查询重新赋值
        model1.order = {
          ...res.data,
          buttonType: res.data.buttonType !== null ? res.data.buttonType : 0,
          weighingMethod:
            res.data.weighingMethod !== null ? res.data.weighingMethod : 0,
          multiCategory:
            res.data.multiCategory !== null ? res.data.multiCategory : 0,
          fileLists: model1.order.fileLists.map((item: any) => {
            return { ...item, fileID: item.id };
          }),
        };
      }
    });
    PictureApi.getAnnex({
      businessId: model1.order.id.toString(),
      orderType: 1,
      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;
  }
  ::v-deep button + button {
    margin-left: 30rpx;
  }
}
</style>
