<template>
  <div>
    <obj-modal
      class="obj-modal"
      ref="modal"
      labelWidth="100px"
      :modalCols="modalCols"
      :modalConfig="modalConfig"
      :modalData="modalData"
      :modalHandles="modalHandles"
    >
    </obj-modal>
  </div>
</template>
<script>
import { debounce, cloneDeep } from "lodash";
const BASE_DATA = {
  calculateMethod: "按重量",
  fareConfig: "全国包邮",
  //为指定地区城市设置运费
  shippingTemplatesRegionList: [
    {
      //默认运费，不限制城市
      cityCodes: "0",
      //首重
      first: 1,
      //首重价格
      firstPrice: 0,
      //续重
      renewal: 1,
      //续重价格
      renewalPrice: 0,
    },
  ],
  //追加
  shippingTemplatesRegionListAppend: [],
  //指定包邮条件
  shippingTemplatesConditionList: [
    // {
    //   cityCodes: "",
    //   price: "",
    //   number: "",
    // },
  ],
};
export default {
  data() {
    return {
      reRender: false,
      currentPanel: "基础信息",
      modalData: {},
      modalConfig: {
        title: "添加运费模板",
        show: false,
        width: "1300px",
        fullscreen: true,
      },
      fileList: [], //回显图片
      place: "", //场地
      linkId: "",
    };
  },
  mounted() {
    window.onbeforeunload = function (e) {
      return "还有未保存的数据，确定离开此页吗？";
    };
  },
  watch: {
    "modalConfig.show"(newVal) {
      if (newVal) {
        //关闭弹窗清空校验
        setTimeout(() => {
          this.$refs.modal.clearValidate();
        });
      }
    },
  },
  methods: {
    toggle(e) {
      if (this.modalConfig.show == false) {
        this.modalConfig.show = true;
      } else {
        this.modalConfig.show = false;
      }
      //回显数据
      const refillData = (e) => {
        let _data = cloneDeep(e);
        console.log("_data", _data);

        //默认运费回显
        _data.shippingTemplatesRegionList =
          _data.shippingTemplatesRegionResultList?.slice(0, 1) ||
          cloneDeep(BASE_DATA.shippingTemplatesRegionList);
        //指定城市设置运费
        _data.shippingTemplatesRegionListAppend =
          _data.shippingTemplatesRegionResultList
            ?.slice(1, _data.shippingTemplatesRegionResultList.length)
            ?.map((item) => {
              item.cityCodes = item.cityCodes.split(",");
              return item;
            }) || cloneDeep(BASE_DATA.shippingTemplatesRegionListAppend);
        //指定包邮条件
        _data.shippingTemplatesConditionList =
          _data.shippingTemplatesConditionResultList?.map((item) => {
            item.cityCodes = item.cityCodes.split(",");
            // item.conditionType=
            if (
              typeof item.price == "number" &&
              typeof item.number == "number"
            ) {
              item.conditionType = "件数+金额";
            } else if (
              typeof item.price == "number" &&
              typeof item.number != "number"
            ) {
              item.conditionType = "金额";
            } else if (
              typeof item.price != "number" &&
              typeof item.number == "number"
            ) {
              item.conditionType = "件数";
            }
            return item;
          }) || cloneDeep(BASE_DATA.shippingTemplatesConditionList);

        //计价方式
        _data.calculateMethod = {
          1: "按件数",
          2: "按重量",
          3: "按体积",
        }[_data.groups];

        //运费配置
        _data.fareConfig = {
          0: "全国包邮",
          2: "自定义运费",
        }[_data.appoint];

        //模板名称
        _data.templateName = _data.name;

        this.modalData = _data;
      };
      return {
        add: (id) => {
          this.$nextTick(() => {
            this.modalData = cloneDeep(BASE_DATA);
          });
          this.linkId = id;
          this.isAdd = true;
          this.modalConfig.title = "添加运费模板";
        },
        update: (e) => {
          this.isAdd = false;
          refillData(e);
          this.modalConfig.title = "编辑运费模板";
        },
        copy: (e) => {
          this.isAdd = true;
          refillData(e);
          this.modalConfig.title = "添加运费模板";
          console.log("this.modalData", this.modalData);

          this.modalData.templateName += "(复制)";
        },
      };
    },
  },
  computed: {
    computedCityOptions() {
      let _arr = cloneDeep(this.$api.mer_admin.getCityOptions());
      return ($rowIndex, list = []) => {
        console.log("计算");

        if (this.reRender == false) {
          return _arr;
        }
        // console.time();
        let selectedArray = new Set();
        for (let i = 0; i < list.length; i++) {
          if (i != $rowIndex) {
            selectedArray = new Set([...selectedArray, ...list[i].cityCodes]);
          }
        }
        // 根据数组过滤树形结构数组
        const filterTreeArray = (tree, bList) => {
          return tree
            .map((item) => {
              item = Object.assign({}, item);
              if (item.children) {
                item.children = filterTreeArray(item.children, bList);
              }
              if (item.children?.length <= 0) {
                return null;
              }
              return item;
            })
            .filter((item) => {
              if (item == null) {
                return false;
              }
              return !bList.has(item.code);
            });
        };
        let new_arr = filterTreeArray(_arr, selectedArray);
        // console.timeEnd();
        return new_arr;
      };
    },
    modalCols() {
      return [
        //模板名称
        {
          label: "模板名称",
          prop: "templateName",
          type: "Input",
          maxlength: "30",
          width: "300px",
          clearable: true,
          placeholder: "请输入模板名称",
          rules: {
            required: true,
            message: "请输入模板名称",
            trigger: "blur,change",
          },
        },
        //计价方式
        {
          label: "计价方式",
          prop: "calculateMethod",
          type: "jsx",
          rules: {
            required: true,
            message: "请选择计价方式",
            trigger: "blur",
          },
          render: () => {
            return (
              <el-radio-group v-model={this.modalData.calculateMethod}>
                <el-radio border label="按重量">
                  按重量
                </el-radio>
                <el-radio border label="按件数">
                  按件数
                </el-radio>
              </el-radio-group>
            );
          },
        },
        //运费配置
        {
          label: "运费配置",
          prop: "fareConfig",
          type: "jsx",
          required: true,
          rules: {
            required: true,
            message: "请选择计价方式",
            trigger: "blur",
          },
          render: () => {
            return (
              <el-radio-group v-model={this.modalData.fareConfig}>
                <el-radio border label="全国包邮">
                  全国包邮
                </el-radio>
                <el-radio border label="自定义运费">
                  自定义运费
                </el-radio>
              </el-radio-group>
            );
          },
        },
        //自定义运费
        {
          label: "自定义运费配置",
          prop: "customShippingFareConfig",
          type: "jsx-out",
          show: this.modalData.fareConfig == "自定义运费",
          render: () => {
            const tableCols = [
              {
                title: "运送到",
                width: "300px",
                field: "cityCodes",
                type: "jsx",
                render: ({ row, $rowIndex }) => {
                  console.log("this.reRender", this.reRender);
                  const change = (e) => {
                    console.log(e);
                    console.log(
                      this.$refs.cityCode
                        .getCheckedNodes()
                        .filter((item) => !(item.parent && item.parent.checked))
                    );
                  };
                  return (
                    <el-form-item
                      label-width="0"
                      prop={
                        "shippingTemplatesRegionListAppend." +
                        $rowIndex +
                        ".cityCodes"
                      }
                      rules={{
                        required: true,
                        message: "请选择运送城市",
                      }}
                    >
                      <el-cascader
                        on-visible-change={(e) => {
                          console.log(e);
                          this.reRender = e;
                        }}
                        ref="cityCode"
                        style="width:100%;"
                        v-model={row.cityCodes}
                        onChange={change}
                        options={this.computedCityOptions(
                          $rowIndex,
                          this.modalData.shippingTemplatesRegionListAppend
                        )}
                        show-all-levels={false}
                        collapse-tags={true}
                        placeholder="点击选择运送城市"
                        props={{
                          props: {
                            multiple: true,
                            checkStrictly: false,
                            emitPath: false,
                            label: "name",
                            value: "code",
                          },
                        }}
                        clearable
                        filterable
                      ></el-cascader>
                    </el-form-item>
                  );
                },
              },
              {
                title:
                  this.modalData.calculateMethod == "按重量"
                    ? "首重（kg）"
                    : "首件（个）",
                field: "first",
                type: "jsx",
                render: ({ row }) => {
                  return (
                    <el-input-number
                      style="width:100%;"
                      min={0}
                      controls={false}
                      precision={
                        this.modalData.calculateMethod == "按重量" ? 2 : 0
                      }
                      v-model={row.first}
                    ></el-input-number>
                  );
                },
              },
              {
                title: "首费（元）",
                field: "firstPrice",
                type: "jsx",
                render: ({ row }) => {
                  return (
                    <el-input-number
                      style="width:100%;"
                      min={0}
                      controls={false}
                      precision={2}
                      v-model={row.firstPrice}
                    ></el-input-number>
                  );
                },
              },
              {
                title:
                  this.modalData.calculateMethod == "按重量"
                    ? "续重（kg）"
                    : "续件数（个）",
                field: "renewal",
                type: "jsx",
                render: ({ row }) => {
                  return (
                    <el-input-number
                      style="width:100%;"
                      min={0}
                      controls={false}
                      precision={
                        this.modalData.calculateMethod == "按重量" ? 2 : 0
                      }
                      v-model={row.renewal}
                    ></el-input-number>
                  );
                },
              },
              {
                title: "续费（元）",
                field: "renewalPrice",
                type: "jsx",
                render: ({ row }) => {
                  return (
                    <el-input-number
                      style="width:100%;"
                      min={0}
                      max={Number(row.firstPrice)}
                      controls={false}
                      precision={2}
                      v-model={row.renewalPrice}
                    ></el-input-number>
                  );
                },
              },
              {
                title: "操作",
                type: "jsx",
                render: (e) => {
                  const remove = () => {
                    console.log(e);
                    this.modalData.shippingTemplatesRegionListAppend.splice(
                      e.rowIndex,
                      1
                    );
                  };
                  const add = () => {
                    console.log(e);
                    this.modalData.shippingTemplatesRegionListAppend.splice(
                      e.rowIndex + 1,
                      0,
                      {
                        //默认运费，不限制城市
                        cityCodes: "",
                        //城市可选的选项
                        cityOptions: [],
                        //首重
                        first: "",
                        //首重价格
                        firstPrice: "",
                        //续重
                        renewal: "",
                        //续重价格
                        renewalPrice: "",
                      }
                    );
                  };
                  return (
                    <div>
                      <el-button type="primary" size="mini" onClick={add}>
                        向下添加
                      </el-button>
                      <el-button type="danger" size="mini" onClick={remove}>
                        删除
                      </el-button>
                    </div>
                  );
                },
              },
            ];
            const addAreaFare = () => {
              this.modalData.shippingTemplatesRegionListAppend.push({
                //默认运费，不限制城市
                cityCodes: "",
                //首重
                first: "",
                //首重价格
                firstPrice: "",
                //续重
                renewal: "",
                //续重价格
                renewalPrice: "",
              });
            };
            return (
              <transition name="el-fade-in">
                <div>
                  <div class="d-flex no-warp justify-start items-center">
                    <el-form-item
                      prop="shippingTemplatesRegionList[0].first"
                      rules={{
                        required: true,
                        message: "请填写默认运费",
                        trigger: "change",
                      }}
                      label="默认运费"
                    >
                      <el-input-number
                        v-model={
                          this.modalData.shippingTemplatesRegionList[0].first
                        }
                        min={0}
                        controls={false}
                        precision={
                          this.modalData.calculateMethod == "按重量" ? 2 : 0
                        }
                      ></el-input-number>
                    </el-form-item>
                    <span style="transform:translateY(-12px);">
                      &nbsp;
                      {this.modalData.calculateMethod == "按重量"
                        ? "kg内"
                        : "件内"}
                      &nbsp;
                    </span>
                    <el-form-item
                      label-width="0"
                      prop="shippingTemplatesRegionList[0].firstPrice"
                      rules={{
                        required: true,
                        message: "请填写默认运费",
                        trigger: "change",
                      }}
                      label=""
                    >
                      <el-input-number
                        v-model={
                          this.modalData.shippingTemplatesRegionList[0]
                            .firstPrice
                        }
                        min={0}
                        controls={false}
                        precision={2}
                      ></el-input-number>
                    </el-form-item>
                    <span style="transform:translateY(-12px);">
                      &nbsp;元，每增加&nbsp;
                    </span>
                    <el-form-item
                      label-width="0"
                      prop="shippingTemplatesRegionList[0].renewal"
                      rules={{
                        required: true,
                        message: "请填写默认运费",
                        trigger: "change",
                      }}
                      label=""
                    >
                      <el-input-number
                        v-model={
                          this.modalData.shippingTemplatesRegionList[0].renewal
                        }
                        min={0}
                        controls={false}
                        precision={
                          this.modalData.calculateMethod == "按重量" ? 2 : 0
                        }
                      ></el-input-number>
                    </el-form-item>
                    <span style="transform:translateY(-12px);">
                      &nbsp;
                      {this.modalData.calculateMethod == "按重量" ? "kg" : "件"}
                      ，增加运费&nbsp;
                    </span>
                    <el-form-item
                      label-width="0"
                      prop="shippingTemplatesRegionList[0].renewalPrice"
                      rules={{
                        required: true,
                        message: "请填写默认运费",
                        trigger: "change",
                      }}
                      label=""
                    >
                      <el-input-number
                        min={0}
                        max={Number(
                          this.modalData.shippingTemplatesRegionList[0]
                            .firstPrice
                        )}
                        controls={false}
                        precision={2}
                        v-model={
                          this.modalData.shippingTemplatesRegionList[0]
                            .renewalPrice
                        }
                      ></el-input-number>
                    </el-form-item>
                    <span style="transform:translateY(-12px);">
                      &nbsp;元&nbsp;
                    </span>
                  </div>
                  <div>
                    <obj-table-plus
                      tableProp={{
                        "scroll-y": {
                          enabled: true,
                        },
                        "show-overflow": true,
                        height: "auto",
                      }}
                      style="height:50vh;"
                      enable-auto-query={false}
                      v-model={this.modalData.shippingTemplatesRegionListAppend}
                      tableCols={tableCols}
                      isPagination={false}
                    >
                      <template slot="empty">
                        <el-button
                          onClick={addAreaFare}
                          type="text"
                          icon="el-icon-plus"
                        >
                          为指定地区城市设置运费（除指定地区外，其余地区的运费按照“默认运费”）
                        </el-button>
                      </template>
                    </obj-table-plus>
                  </div>
                </div>
              </transition>
            );
          },
        },
        //指定包邮条件
        {
          label: "",
          prop: "123",
          type: "jsx-out",
          show: this.modalData.fareConfig == "自定义运费",
          render: () => {
            const tableCols = [
              {
                title: "运送到",
                width: "300px",
                field: "cityCodes",
                type: "jsx",
                render: ({ row, $rowIndex }) => {
                  const change = (e) => {
                    console.log(e);
                  };
                  return (
                    <el-form-item
                      label-width="0"
                      prop={
                        "shippingTemplatesConditionList." +
                        $rowIndex +
                        ".cityCodes"
                      }
                      rules={{
                        required: true,
                        message: "请选择运送城市",
                      }}
                    >
                      <el-cascader
                        style="width:100%;"
                        v-model={row.cityCodes}
                        onChange={change}
                        on-visible-change={(e) => {
                          console.log(e);
                          this.reRender = e;
                        }}
                        options={this.computedCityOptions(
                          $rowIndex,
                          this.modalData.shippingTemplatesConditionList
                        )}
                        show-all-levels={false}
                        placeholder="点击选择运送城市"
                        collapse-tags={true}
                        props={{
                          props: {
                            multiple: true,
                            checkStrictly: false,
                            emitPath: false,
                            label: "name",
                            value: "code",
                          },
                        }}
                        clearable
                        filterable
                      ></el-cascader>
                    </el-form-item>
                  );
                },
              },
              {
                title: "包邮条件",
                field: "conditions",
                type: "jsx",
                render: ({ row }) => {
                  const _conditionMapper = {
                    件数: (
                      <div>
                        <el-input-number
                          style="width:150px;"
                          min={0}
                          controls={false}
                          precision={0}
                          v-model={row.number}
                        ></el-input-number>
                        <span>&nbsp;件包邮&nbsp;</span>
                      </div>
                    ),
                    金额: (
                      <div>
                        <el-input-number
                          style="width:150px;"
                          min={0}
                          controls={false}
                          precision={2}
                          v-model={row.price}
                        ></el-input-number>
                        <span>&nbsp;元包邮&nbsp;</span>
                      </div>
                    ),
                    "件数+金额": (
                      <div>
                        <el-input-number
                          style="width:150px;"
                          min={0}
                          controls={false}
                          precision={0}
                          v-model={row.number}
                        ></el-input-number>
                        <span>&nbsp;件，且&nbsp;</span>
                        <el-input-number
                          style="width:150px;"
                          min={0}
                          controls={false}
                          precision={2}
                          v-model={row.price}
                        ></el-input-number>
                        <span>&nbsp;元以上包邮&nbsp;</span>
                      </div>
                    ),
                  };
                  return (
                    <div class="flex justify-start items-center">
                      <el-select
                        style="width:120px;"
                        v-model={row.conditionType}
                      >
                        <el-option label="件数" value="件数"></el-option>
                        <el-option label="金额" value="金额"></el-option>
                        <el-option
                          label="件数+金额"
                          value="件数+金额"
                        ></el-option>
                      </el-select>
                      <span>&nbsp;满&nbsp;</span>
                      {_conditionMapper[row.conditionType]}
                    </div>
                  );
                },
              },
              {
                title: "操作",
                width: "200px",
                type: "jsx",
                render: (e) => {
                  const remove = () => {
                    console.log(e);
                    this.modalData.shippingTemplatesConditionList.splice(
                      e.rowIndex,
                      1
                    );
                  };
                  const add = () => {
                    console.log(e);
                    this.modalData.shippingTemplatesConditionList.splice(
                      e.rowIndex + 1,
                      0,
                      {
                        cityCodes: "",
                        price: "",
                        number: "",
                        conditionType: "件数",
                      }
                    );
                  };
                  return (
                    <div>
                      <el-button type="primary" size="mini" onClick={add}>
                        向下添加
                      </el-button>
                      <el-button type="danger" size="mini" onClick={remove}>
                        删除
                      </el-button>
                    </div>
                  );
                },
              },
            ];
            const addAreaFare = () => {
              this.modalData.shippingTemplatesConditionList.push({
                cityCodes: "",
                price: "",
                number: "",
                conditionType: "件数",
              });
            };
            return (
              <transition name="el-fade-in">
                <obj-table-plus
                  class="mt-5"
                  style="height:50vh;"
                  enable-auto-query={false}
                  v-model={this.modalData.shippingTemplatesConditionList}
                  tableCols={tableCols}
                  isPagination={false}
                >
                  <template slot="empty">
                    <el-button
                      onClick={addAreaFare}
                      type="text"
                      icon="el-icon-plus"
                    >
                      添加其他地区/其他包邮条件
                    </el-button>
                  </template>
                </obj-table-plus>
              </transition>
            );
          },
        },
      ];
    },
    modalHandles() {
      return [
        {
          label: "关闭",
          type: "",
          handle: debounce(() => {
            this.toggle();
          }, 300),
        },
        {
          label: "确认",
          type: "primary",
          loading: this.isLoading,
          submit: true,
          handle: debounce(() => {
            console.log(this.modalData);
            if (this.isAdd) {
              this.$api.mer_admin
                .addShippingTemplate({
                  linkId: this.linkId,
                  defaults: 0, //默认值，待确认
                  sort: 0, //默认值，待确认
                  type: 2, //默认值，待确认
                  name: this.modalData.templateName,
                  groups: {
                    按重量: 2,
                    按件数: 1,
                    按体积: 3,
                  }[this.modalData.calculateMethod],
                  appoint: {
                    全国包邮: 0,
                    自定义运费: 2,
                  }[this.modalData.fareConfig],
                  shippingTemplatesRegionList:
                    this.modalData.fareConfig == "全国包邮"
                      ? null
                      : [
                          ...this.modalData.shippingTemplatesRegionList,
                          ...JSON.parse(
                            JSON.stringify(
                              this.modalData.shippingTemplatesRegionListAppend.map(
                                (item) => {
                                  item.cityCodes = item.cityCodes.join(",");
                                  return item;
                                }
                              )
                            )
                          ),
                        ],
                  shippingTemplatesConditionList:
                    this.modalData.fareConfig == "全国包邮"
                      ? null
                      : JSON.parse(
                          JSON.stringify(
                            this.modalData.shippingTemplatesConditionList.map(
                              (item) => {
                                item.cityCodes = item.cityCodes.join(",");
                                //过滤
                                if (item.conditionType == "件数") {
                                  item.price = null;
                                } else if (item.conditionType == "金额") {
                                  item.number = null;
                                }
                                return item;
                              }
                            )
                          )
                        ),
                })
                .then((res) => {
                  this.toggle();
                  this.$emit("refresh");
                });
            } else {
              //编辑
              this.$api.mer_admin
                .updateShippingTemplate({
                  id: this.modalData.id,
                  linkId: this.linkId,
                  defaults: 0, //默认值，待确认
                  sort: 0, //默认值，待确认
                  type: 2, //默认值，待确认
                  name: this.modalData.templateName,
                  groups: {
                    按重量: 2,
                    按件数: 1,
                    按体积: 3,
                  }[this.modalData.calculateMethod],
                  appoint: {
                    全国包邮: 0,
                    自定义运费: 2,
                  }[this.modalData.fareConfig],
                  shippingTemplatesRegionList:
                    this.modalData.fareConfig == "全国包邮"
                      ? null
                      : [
                          ...this.modalData.shippingTemplatesRegionList,
                          ...JSON.parse(
                            JSON.stringify(
                              this.modalData.shippingTemplatesRegionListAppend.map(
                                (item) => {
                                  item.cityCodes = item.cityCodes.join(",");
                                  return item;
                                }
                              )
                            )
                          ),
                        ],
                  shippingTemplatesConditionList:
                    this.modalData.fareConfig == "全国包邮"
                      ? null
                      : JSON.parse(
                          JSON.stringify(
                            this.modalData.shippingTemplatesConditionList.map(
                              (item) => {
                                item.cityCodes = item.cityCodes.join(",");
                                //过滤
                                if (item.conditionType == "件数") {
                                  item.price = null;
                                } else if (item.conditionType == "金额") {
                                  item.number = null;
                                }
                                return item;
                              }
                            )
                          )
                        ),
                })
                .then((res) => {
                  this.toggle();
                  this.$emit("refresh");
                });
            }
          }, 300),
        },
      ];
    },
  },
  asyncComputed: {
    async getCityOptions() {
      let res = await this.$api.mer_admin.getCity();
      return res.data.data;
    },
    // async getProductCategory() {
    //   let res = await this.$api.mer_admin.getProductCategory();
    //   return res.data.data;
    // },
    // async getSaleUnit() {
    //   let res = await this.$api.mer_admin.getSaleUnit({
    //     shopId: JSON.parse(sessionStorage.getItem("userInfo")).shopId,
    //   });
    //   console.log(res);

    //   return res.data.data;
    // },
  },
};
</script>
<style lang="scss" scoped>
.obj-modal ::v-deep {
  .el-dialog__body {
    padding: 0 30px;
  }
}
</style>