<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"
      >
        <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
          :customStyle="{}"
          border="none"
          :disabled="item.disabled || item.type === 'select'"
          :disabledColor="['补单时间','过磅设备','客户','出货产品'].indexOf(item.name) > -1?'#ffffff':'#f5f7fa'"
          @change="(e:any) => {handleInput(e, item)}"
          @clear="handleClear(item)"
        >
          <template #suffix>
            <text v-if="item.key === 'subtractNum'">
              {{ model1.order.buttonType === 1 ? 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 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>
    <u-datetime-picker
      :show="contrlModalParams.isShowSplTime"
      v-model="contrlModalParams.spltime"
      mode="datetime"
      @confirm="(v: any) => {handleTime(v)}"
      @cancel="contrlModalParams.isShowSplTime = false"
      :closeOnClickOverlay="true"
      @close="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' && item.childKey"
        :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>

  <!-- 出货产品弹框 -->
  <ProductDialog
    :show="showDialog.showProduct"
    @handleDialog="(v:boolean) => {handleDialog('showProduct', v)}"
    @changeProduct="changeProduct"
    ref="productRef"
    :isShipment="true"
  ></ProductDialog>
</template>
<script setup lang="ts">
import {
  CustomerApi,
  DeviceApi,
  GoodsApi,
  PictureApi,
  ShipmentApi,
} from "@/services";
import { countDots, formatDate } from "@/utils";
import { DeviceType, ImagesType, OrderType } from "@/utils/enum";
import _ from "underscore";
import ProductDialog from "@/components/Dialog/ProductDialog.vue";
import valid from "@/utils/validate";
import { onLoad } from "@dcloudio/uni-app";
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 === "grossWeight" || item.key === "tare") {
    const temp = e?.replace(valid.valid_decimal.pattern, "");
    if (countDots(temp).length > 1) {
      uni.showToast({
        title: "请输入正确的" + item.name,
        icon: "none",
      });
      return;
    }
    setTimeout(() => {
      model1.order[item.key] = temp;
    }, 10);
  }

  if (item.key === "number" ) {
    const temp = e?.replace(valid.valid_number, "");
    if (countDots(temp).length > 1) {
      uni.showToast({
        title: "请输入正确的" + item.name,
        icon: "none",
      });
      return;
    }
    setTimeout(() => {
      model1.order[item.key] = temp;
    }, 10);
  }
};

const model1 = reactive<any>({
  order: {
    deliveryMethod: 0,
    fileLists: [],
    splTime: "",
    subtractType: 1,
    netWeight: 0,
    repairTime: formatDate(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
  },
});
const rules = reactive({
  "order.repairTime": {
    type: "string",
    required: true,
    message: "请选择补单时间",
    trigger: ["blur", "change"],
  },
  "order.deviceName": {
    type: "string",
    required: true,
    message: "请选择过磅设备",
    trigger: ["blur", "change"],
  },
  "order.userName": {
    type: "string",
    required: true,
    message: "请选择客户",
    trigger: ["blur", "change"],
  },
  "order.productName": {
    type: "string",
    required: true,
    message: "请选择出货产品",
    trigger: ["blur", "change"],
  },
  "order.number": {
    type: "number",
    required: true,
    message: "请输入数量",
    trigger: ["blur", "change"],
  },
  "order.grossWeight": {
    type: "number",
    required: true,
    message: "请输入毛重",
    trigger: ["blur", "change"],
  },
  "order.tare": {
    type: "number",
    required: true,
    message: "请输入皮重",
    trigger: ["blur", "change"],
  },
});
const contrlModalParams = reactive<any>({
  isShowSplTime: false,
  spltime: Number(new Date()),
  device: {
    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",
    required: true,
    unit: "",
    fn: () => {
      uni.navigateTo({
        url: `/pagesApp/supplierOrCustomerList?isShipment=true`,
      });
    },
  },
  {
    name: "出货产品",
    key: "productName",
    type: "select",
    childKey: "product",
    required: true,
    unit: "",
    fn: () => {
      // contrlModalParams.product.isShow = true;
      // contrlModalParams.product.title = "收货产品";
      handleDialog("showProduct", true);
      uni.hideKeyboard();
    },
  },
  {
    name: "数量",
    key: "number",
    type: "input",
    required: true,
    unit: "件",
  },
  {
    name: "毛重",
    key: "grossWeight",
    type: "input",
    required: true,
    unit: "KG",
  },
  {
    name: "皮重",
    key: "tare",
    type: "input",
    required: true,
    unit: "KG",
  },
  {
    name: "净重",
    key: "netWeight",
    type: "input",
    required: true,
    disabled: true,
    unit: "KG",
  },
  {
    name: "提货方式",
    key: "deliveryMethod",
    type: "radio",
    required: true,
    unit: "",
    child: [
      {
        id: 0,
        name: "送货",
      },
      {
        id: 1,
        name: "自提",
      },
    ],
  },
  {
    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",
  },
  {
    name: "备注",
    key: "notes",
    type: "textarea",
  },
  {
    name: "货品照片",
    key: "photo",
    type: "upload",
  },
]);

// 监听毛重 皮重
watch(
  [() => model1.order.grossWeight, () => model1.order.tare],
  ([grossWeightNew, tareNew]) => {
    /**
     * 过磅净重： 毛重-皮重
      结算重量： 过磅净重-扣杂
      预估总价： 结算单价*结算重量
      实际收入：实际结算金额-运费-杂费
     */
    model1.order.netWeight = (grossWeightNew || 0) - (tareNew || 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 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: "已删除" });
      }
    });
  }
};
const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "user") {
    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;
  }
};
// 产品信息
GoodsApi.getShipmentProductList().then((res) => {
  if (res.code === 200) {
    contrlModalParams.product.list = _.map(
      res.data as any,
      function (item: any) {
        return { name: item.shmProductsName, ...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) {
          console.log("*** 资源文件更新成功");
        }
      });
    }
  });
};

/**
 * 校验
 */
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;
    }
  }

  if (parseFloat(model1.order.tare) > parseFloat(model1.order.grossWeight)) {
    uni.showToast({
      title: `毛重需大于皮重`,
      icon: "none",
    });
    return;
  }
  check().then((res) => {
    if (res) {
      startSave();
    }
  });
};

const startSave = () => {
  ShipmentApi.addOrderOut(model1.order).then((res) => {
    if (res.code === 200) {
      model1.order.id = res.data;
      upload();
      uni.navigateBack()
    }
  });
};
const handleTime = (v: any) => {
  model1.order.repairTime = formatDate(v.value, "{y}-{m}-{d} {h}:{i}:{s}");
  contrlModalParams.isShowSplTime = false;
};

onLoad((option: any) => {
  uni.$on("getCustomer", (data) => {
    model1.order.userName = data.item.name; // 供应商名称
    model1.order.userId = data.item.id; // 供应商Id,
  });
});

onUnmounted(() => {
  uni.$off("getSupplier", () => {});
});
</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: fixed;
width: calc(100vw - 100rpx);
  bottom: 0rpx;
  z-index: 999;
  ::v-deep button {
    border-radius: 43rpx;
  }
}
</style>
