<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 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>
            {{ item.unit }}
          </template>
        </u-input>
        <!-- @afterRead="afterRead"
          @delete="deletePic" -->
        <!-- <u-upload
          v-if="item.type === 'upload'"
          :fileList="[]"
          name="1"
          multiple
          :maxCount="10"
        ></u-upload> -->

        <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 as any)]"
          placement="row"
        >
          <u-radio activeColor="#00DCEE" label="送货" :name="0"></u-radio>
          &nbsp;&nbsp;&nbsp;
          <u-radio activeColor="#00DCEE" label="自提" :name="1"></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"
        :safeAreaInsetBottom="true"
      ></u-action-sheet>
    </block>
  </view>
  <view class="btn-box">
    <u-button type="primary" text="保存" @click="save()"></u-button>
  </view>

  <!-- 出货产品弹框 -->
  <ProductDialog
    :show="showDialog.showProduct"
    @handleDialog="(v:boolean) => {handleDialog('showProduct', v)}"
    @changeProduct="changeProduct"
    ref="productRef"
    :isShipment="true"
  ></ProductDialog>
</template>
<script setup lang="ts">
import { CustomerApi, GoodsApi, PictureApi, ShipmentApi } from "@/services";
import type { ComType } from "@/types/global";
import { ImagesType, OrderType, ScaleStatus } from "@/utils/enum";
import { onLoad } from "@dcloudio/uni-app";
import _ from "underscore";
import ProductDialog from "../components/ProductDialog.vue";
import valid from "@/utils/validate";
const handleClear = (item:any) => {
  (model1.order as any)[item.key] = '';
}
// 供应商选择
const showDialog = <
  {
    [key: string]: boolean;
  }
>reactive({
  showProduct: false,
});

const handleDialog = (key: string, v: boolean) => {
  showDialog[key] = v;
};

// 收货产品选择
const changeProduct = (obj: any) => {
  model1.order.productName = obj.shmProductsName; // 收货产品名称
  model1.order.productId = obj.id; // 收货产品Id,
};

// 数量
const handleInput = (e: any, item: any) => {
  if (item.key === "number" || item.key === "phone") {
    const tempPrice = e?.replace(valid.valid_number, "");
    setTimeout(() => {
      model1.order[item.key] = tempPrice;
    }, 10);
  }
};
const model1 = reactive<any>({
  order: {
    id: 0,
    splTime: "",
    takeType: 1,
    fileLists: [],
  },
});
const rules = reactive({
  "order.userName": {
    type: "string",
    required: true,
    message: "请选择客户",
    trigger: ["blur", "change"],
  },
  "order.productName": {
    type: "string",
    required: true,
    message: "请选择出货产品名称",
    trigger: ["blur", "change"],
  },
  "order.tare": {
    type: "number",
    required: true,
    message: "请输入皮重",
    trigger: ["blur", "change"],
  },
  "order.number": {
    type: "number",
    required: true,
    message: "数量为空或数量输入错误",
    trigger: ["blur", "change"],
  },
  "order.weighingMethod": {
    type: "number",
    required: true,
    message: "请选择称重方式",
    trigger: ["blur", "change"],
  },
  "order.deliveryMethod": {
    type: "number",
    required: true,
    message: "请选择提货方式",
    trigger: ["blur", "change"],
  },
});
const contrlModalParams = reactive<ComType>({
  userSelect: {
    isShow: false,
    title: "标题",
    list: [],
  },
  productSelect: {
    isShow: false,
    title: "标题",
    list: [],
  },
});

const formAttrList = reactive<ComType>([
  {
    name: "客户",
    key: "userName",
    type: "select",
    required: true,
    childKey: "userSelect",
    unit: "",
    fn: () => {
      // contrlModalParams.userSelect.isShow = true;
      // contrlModalParams.userSelect.title = "客户";
      uni.hideKeyboard();
    },
  },
  {
    name: "出货产品",
    key: "productName",
    type: "select",
    required: true,
    childKey: "productSelect",
    unit: "",
    fn: () => {
      // contrlModalParams.productSelect.isShow = true;
      // contrlModalParams.productSelect.title = "出货产品";
      handleDialog("showProduct", true);
      uni.hideKeyboard();
    },
  },
  {
    name: "数量",
    key: "number",
    type: "input",
    required: true,
    unit: "件",
  },
  {
    name: "皮重",
    key: "tare",
    type: "input",
    required: true,
    unit: "KG",
    disabled: true
  },
  {
    name: "提货方式",
    key: "deliveryMethod",
    required: true,
    type: "radio",
  },
  {
    name: "车辆信息",
    type: "text",
  },
  {
    name: "车牌号",
    key: "carNumber",
    type: "input",
    unit: "",
  },
  {
    name: "司机电话",
    key: "phone",
    type: "input",
    unit: "",
  },
  {
    name: "集装箱",
    type: "text",
  },
  {
    name: "箱号",
    key: "box",
    type: "input",
    unit: "",
  },
  {
    name: "封号",
    key: "title",
    type: "input",
    unit: "",
  },
  {
    name: "备注",
    key: "notes",
    type: "textarea",
  },
  {
    name: "上传照片",
    key: "photo",
    type: "upload",
  },
]);

CustomerApi.getCustomUserList({}).then((res) => {
  if (res.code === 200) {
    contrlModalParams.userSelect.list = res.data;
  }
});
GoodsApi.getShipmentProductList().then((res) => {
  if (res.code === 200) {
    contrlModalParams.productSelect.list = _.map(
      res.data as any,
      function (item: any) {
        return { name: item.shmProductsName, ...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 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 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 = () => {
  if (model1.order.carNumber) {
    if (!valid.carNo.pattern.test(model1.order.carNumber)) {
      uni.showToast({ icon: "none", title: "请输入正确的车牌号" });
      return;
    }
  }
  if (model1.order.phone) {
    if (!valid.mobile.pattern.test(model1.order.phone)) {
      uni.showToast({ icon: "none", title: "请输入正确的手机号" });
      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 = () => {
  // 编辑更新状态值
  // else if (state.scaleStatus === ScaleStatus.ToBeGrossWeight) {
  //   status = ScaleStatus.ToBeShipmentReview;
  // }
  let status = 0;
  if (state.scaleStatus === ScaleStatus.ToBeShipment) {
    status = ScaleStatus.ToBeGrossWeight;
  } else {
    status = model1.order.scaleStatus;
  }
  ShipmentApi.updateOrderIn({
    orderOutPos: [{ ...model1.order, scaleStatus: status }],
  }).then((res) => {
    if (res.code === 200) {
      uni.showToast({
        title: "编辑成功",
        icon: "success",
      });
      uni.navigateBack()
      // if (state.scaleStatus === ScaleStatus.ToBeShipment || state.scaleStatus === ScaleStatus.ToBeGrossWeight) {
      //   // uni.redirectTo({
      //   //   url: "/pagesShipment/shipmenting?scaleStatus=" + state.scaleStatus, // 要跳转到的页面路径
      //   // });
       
      // } else {
      //   uni.navigateBack()
      //   // uni.redirectTo({
      //   //   url:
      //   //     "/pagesShipment/review/index?id=" +
      //   //     model1.order.id +
      //   //     `&scaleStatusBtnType=1`, // 要跳转到的页面路径
      //   // });
      // }
    }
  });
};

const state = reactive({
  scaleStatus: 0,
});
onLoad((option) => {
  model1.order.id = (option as any).id;
  state.scaleStatus = parseInt((option as any).scaleStatus);
  if (state.scaleStatus === ScaleStatus.ToBeShipment) {
    uni.setNavigationBarTitle({
      title: "待出货编辑",
    });
  } else if (state.scaleStatus === ScaleStatus.ToBeGrossWeight) {
    uni.setNavigationBarTitle({
      title: "待过毛重编辑",
    });
  } else {
    uni.setNavigationBarTitle({
      title: "编辑出货",
    });
  }
  if (model1.order.id) {
    ShipmentApi.getDetailById({ id: model1.order.id }).then((res) => {
      if (res.code === 200) {
        model1.order = {
          ...res.data,
          deliveryMethod:
            res.data.deliveryMethod !== null ? res.data.deliveryMethod : 0,
          fileLists: model1.order.fileLists.map((item: any) => {
            return { ...item, fileID: item.id };
          }),
        };
        console.log(model1.order);
      }
    });
    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>
