<template>
  <u-popup
    :show="show"
    mode="bottom"
    :round="10"
    :closeable="false"
    @close="handleClose"
  >
    <view class="box">
      <view v-if="!isShipment">
        <u-cell-group :border="false">
          <u-cell
            v-for="(item, index) in formAttrList"
            :key="index"
            :title="item.name"
            :titleStyle="{
              fontSize: '26rpx',
              color: 'rgba(0, 0, 0, 1)',
              fontWeight: 'bold',
            }"
            isLink
            @click="item.fn"
            :value="getValue(item.name)"
          ></u-cell>
        </u-cell-group>
        <view class="title">收货单类型</view>
        <view class="btn-box">
          <view v-for="(item, index) in splBtnList" :key="index">
            <u-button
              :text="item.name"
              plain
              shape="circle"
              type="info"
              size="small"
              :customStyle="
                item.key === currentSpl
                  ? { border: '1px solid #00dcee', color: '#00dcee' }
                  : ''
              "
              @click="currentSpl = item.key"
            ></u-button>
          </view>
        </view>
        <view class="title">收货单价区间</view>
        <view class="range">
          <view>
            <u-input
              shape="circle"
              :fontSize="12"
              :placeholderStyle="{ fontSize: '12px' }"
              placeholder="最低价"
              type="number"
              size="small"
              v-model="state.minPrice"
              @change="(e:any) => {handleInput(e, {key: 'minPrice', name: '最低价'})}"
            ></u-input
          ></view>
          -
          <view>
            <u-input
              shape="circle"
              :fontSize="12"
              :placeholderStyle="{ fontSize: '12px' }"
              placeholder="最高价"
              type="number"
              size="small"
              v-model="state.maxPrice"
              @change="(e:any) => {handleInput(e, {key: 'maxPrice', name: '最高价'})}"
            ></u-input
          ></view>
        </view>
      </view>
      <!-- 出货参数 -->
      <view v-else>
        <u-cell-group :border="false">
          <u-cell
            v-for="(item, index) in formAttrList1"
            :key="index"
            :title="item.name"
            :titleStyle="{
              fontSize: '26rpx',
              color: 'rgba(0, 0, 0, 1)',
              fontWeight: 'bold',
            }"
            isLink
            @click="item.fn"
            :value="getValue(item.name)"
          ></u-cell>
        </u-cell-group>

        <view class="title">提货方式</view>
        <view class="btn-box">
          <view v-for="(item, index) in deliveryMethodBtnList" :key="index">
            <u-button
              :text="item.name"
              plain
              shape="circle"
              type="info"
              size="small"
              :customStyle="
                item.key === deliveryMethod
                  ? { border: '1px solid #00dcee', color: '#00dcee' }
                  : ''
              "
              @click="deliveryMethod = item.key"
            ></u-button>
          </view>
        </view>
      </view>

      <view class="btn-box1">
        <u-button
          text="重置"
          color="#E8E8E8"
          :customStyle="{ color: '#999' }"
          shape="circle"
          @click="resetState"
        ></u-button>
        <u-button
          type="primary"
          text="确定"
          shape="circle"
          @click="getFilter()"
        ></u-button>
      </view>
    </view>

    <block v-for="(item, index) in formAttrList" :key="index">
      <u-action-sheet
        :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>
    <block v-for="(item, index) in formAttrList1" :key="index">
      <u-action-sheet
        :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>
  </u-popup>

  <!-- 供应商选择弹框 -->
  <SupplierDialog
    ref="supplierDialog"
    :show="showDialog.showSupplier"
    @handleDialog="(v:boolean) => {handleDialog('showSupplier', v)}"
    @changeUser="changeUser"
    :isShipment="isShipment"
  ></SupplierDialog>
  <!-- 收货产品弹框 -->
  <ProductDialog
    :show="showDialog.showProduct"
    @handleDialog="(v:boolean) => {handleDialog('showProduct', v)}"
    @changeProduct="changeProduct"
    ref="productRef"
    :isShipment="isShipment"
  ></ProductDialog>
</template>
<script setup lang="ts">
import { CustomerApi, GoodsApi, ProfileApi, SupplierApi } from "@/services";
import SupplierDialog from "./SupplierDialog.vue";
import ProductDialog from "./ProductDialog.vue";
import _ from "underscore";
import valid from "@/utils/validate";
import { countDots } from "@/utils";
// 供应商选择
const showDialog = <
  {
    [key: string]: boolean;
  }
>reactive({
  showSupplier: false,
  showProduct: false,
});

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

const changeUser = (obj: any) => {
  state.userName = obj.name; // 供应商名称
  state.userId = obj.id; // 供应商Id,
};

// 收货产品选择
const changeProduct = (obj: any) => {
  if (props.isShipment) {
    state.productName = obj.shmProductsName; // 收货产品名称
  } else {
    state.productName = obj.reProductsName; // 收货产品名称
  }
  state.productId = obj.id; // 收货产品Id,
};

const handleInput = (e: any, item: any) => {
  if (["minPrice", "maxPrice"].indexOf(item.key) > -1) {
    const temp = e?.replace(valid.valid_decimal.pattern, "");
    if (countDots(temp).length > 1) {
      uni.showToast({
        title: "请输入正确的" + item.name,
        icon: "none",
      });
    }

    if (item.key === "maxPrice" || item.key === "minPrice") {
      if (state.minPrice && state.maxPrice && state.minPrice > state.maxPrice) {
        uni.showToast({
          title: `最大值应小于最小值`,
          icon: "none",
        });
        return;
      }
    }

    setTimeout(() => {
      (state as any)[item.key] = temp;
    }, 10);
  }
};

const props = defineProps<{
  show: boolean;
  isShipment: boolean;
}>();
const emit = defineEmits(["handleDialog", "handleOk"]);
const handleClose = () => {
  emit("handleDialog", false);
};
const state = reactive({
  userId: null, // 供应商ID
  userName: "", // 供应商名称
  pricingUserId: null, // 定价人id
  pricingUserName: "", // 定价人名称
  productId: null, // 产品id,
  productName: "", // 产品名称
  minPrice: null,
  maxPrice: null,
});
const currentSpl = ref<any>(null);
const splBtnList = [
  { key: null, name: "全部" },
  { key: true, name: "手工补单" },
  { key: false, name: "系统单" },
];
const deliveryMethod = ref<any>(null);
const deliveryMethodBtnList = [
  { key: null, name: "全部" },
  { key: 0, name: "送货" },
  { key: 1, name: "自提" },
];
const formAttrList = reactive<any>([
  {
    name: "供应商",
    childKey: "supplier",
    fn: () => {
      // contrlModalParams.supplier.isShow = true;
      // contrlModalParams.supplier.title = "供应商";
      handleDialog("showSupplier", true);
      uni.hideKeyboard();
    },
  },
  {
    name: "收货产品",
    childKey: "product",
    fn: () => {
      // contrlModalParams.product.isShow = true;
      // contrlModalParams.product.title = "收货产品";
      handleDialog("showProduct", true);
      uni.hideKeyboard();
    },
  },
  {
    name: "定价人",
    childKey: "user",
    fn: () => {
      contrlModalParams.user.isShow = true;
      contrlModalParams.user.title = "定价人";
    },
  },
]);

const formAttrList1 = reactive<any>([
  {
    name: "客户",
    childKey: "customer",
    fn: () => {
      // contrlModalParams.customer.isShow = true;
      // contrlModalParams.customer.title = "客户";
      handleDialog("showSupplier", true);
      uni.hideKeyboard();
    },
  },
  {
    name: "出货产品",
    childKey: "shipmentProduct",
    fn: () => {
      // contrlModalParams.shipmentProduct.isShow = true;
      // contrlModalParams.shipmentProduct.title = "出货产品";
      handleDialog("showProduct", true);
      uni.hideKeyboard();
    },
  },
]);
const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "supplier") {
    state.userName = v.name;
    state.userId = v.id;
  } else if (key === "product") {
    state.productName = v.name;
    state.productId = v.id;
  } else if (key === "user") {
    state.pricingUserName = v.name;
    state.pricingUserId = v.id;
  } else if (key === "customer") {
    state.userName = v.name;
    state.userId = v.id;
  } else if (key === "shipmentProduct") {
    state.productName = v.name;
    state.productId = v.id;
  }
};
const getValue = (v: string) => {
  if (v === "供应商") {
    return state.userName;
  } else if (v === "收货产品") {
    return state.productName;
  } else if (v === "定价人") {
    return state.pricingUserName;
  } else if (v === "客户") {
    return state.userName;
  } else if (v === "出货产品") {
    return state.productName;
  }
};
const contrlModalParams = reactive<any>({
  supplier: {
    isShow: false,
    title: "标题",
    list: [],
  },
  product: {
    isShow: false,
    title: "标题",
    list: [],
  },
  user: {
    isShow: false,
    title: "标题",
    list: [],
  },
  customer: {
    isShow: false,
    title: "标题",
    list: [],
  },
  shipmentProduct: {
    isShow: false,
    title: "标题",
    list: [],
  },
});
// 定价人
ProfileApi.getUserList({}).then((res: any) => {
  if (res.code === 200) {
    contrlModalParams.user.list = res.data;
  }
});
// 供应商
SupplierApi.getSupplierUserList({}).then((res: any) => {
  if (res.code === 200) {
    contrlModalParams.supplier.list = res.data;
  }
});
// 收货产品
GoodsApi.getReceiveProductList().then((res: any) => {
  if (res.code === 200) {
    contrlModalParams.product.list = _.map(
      res.data as any,
      function (item: any) {
        return { name: item.reProductsName, ...item };
      }
    );
  }
});
// 客户信息
CustomerApi.getCustomUserList({}).then((res) => {
  if (res.code === 200) {
    contrlModalParams.customer.list = res.data;
  }
});
// 产品信息
GoodsApi.getShipmentProductList().then((res) => {
  if (res.code === 200) {
    contrlModalParams.shipmentProduct.list = _.map(
      res.data as any,
      function (item: any) {
        return { name: item.shmProductsName, ...item };
      }
    );
  }
});

// 重置 确定
const resetState = () => {
  state.userId = null; // 供应商ID
  state.userName = ""; // 供应商名称
  state.pricingUserId = null; // 定价人id
  state.pricingUserName = ""; // 定价人名称
  state.productId = null; // 产品id,
  state.productName = ""; // 产品名称
  state.minPrice = null;
  state.maxPrice = null;
  currentSpl.value = null;
  deliveryMethod.value = null;
};

const getFilter = () => {
  if (state.minPrice && state.maxPrice && state.minPrice > state.maxPrice) {
    uni.showToast({
      title: `最大值应小于最小值`,
      icon: "none",
    });
    return;
  }
  emit("handleOk", {
    ...state,
    repairFlag: currentSpl.value,
    deliveryMethod: deliveryMethod.value,
  });
  emit("handleDialog", false);
};
</script>
<style lang="scss" scoped>
.box {
  padding: 60rpx 30rpx 150rpx;
  ::v-deep .u-cell__value {
    font-size: 26rpx;
  }
  .title {
    font-size: 26rpx;
    color: rgba(0, 0, 0, 1);
    font-weight: bold;
    padding-left: 30rpx;
    padding-top: 20rpx;
    padding-bottom: 20rpx;
  }
  .btn-box {
    flex-direction: row;
    display: flex;
    align-items: center;
    padding-left: 30rpx;
    > view + view {
      margin-left: 20rpx;
    }
  }
  .range {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 30rpx;
    > view {
      width: 40%;
    }
  }

  .btn-box1 {
    position: fixed;
    bottom: 0;
    left: 0;
    margin: 30rpx;
    width: calc(100% - 60rpx);
    display: flex;
    ::v-deep button + button {
      margin-left: 50rpx;
    }
  }
}
</style>
