<template>
  <div>
    <obj-modal
      class="obj-modal"
      ref="modal"
      labelWidth="100px"
      :modalCols="modalCols"
      :modalConfig="modalConfig"
      :modalData="modalData"
      :modalHandles="modalHandles"
    >
      <template slot="dialog__before">
        <!-- <el-tabs v-model="currentPanel">
                    <el-tab-pane label="基础信息" name="基础信息"></el-tab-pane>
                    <el-tab-pane label="销售信息" name="销售信息"></el-tab-pane>
                    <el-tab-pane label="其他信息" name="其他信息"></el-tab-pane>
                </el-tabs> -->
      </template>
    </obj-modal>
  </div>
</template>
<script>
import { debounce, cloneDeep } from "lodash";
const BASE_DATA = {
  calculateMethod: "按重量",
  fareConfig: "全国包邮",
  //为指定地区城市设置运费
  shippingTemplatesRegionList: [
    {
      //默认运费，不限制城市
      cityCodes: "0",
      //首重
      first: "",
      //首重价格
      firstPrice: "",
      //续重
      renewal: "",
      //续重价格
      renewalPrice: "",
    },
  ],
  //追加
  shippingTemplatesRegionListAppend: [],
  //指定包邮条件
  shippingTemplatesConditionList: [
    // {
    //   cityCodes: "",
    //   price: "",
    //   number: "",
    // },
  ],
};
export default {
  data() {
    return {
      currentPanel: "基础信息",
      modalData: {},
      modalConfig: {
        title: "添加运费模板",
        show: false,
        width: "1300px",
        fullscreen: true,
      },
      fileList: [], //回显图片
      place: "", //场地
    };
  },
  mounted() {},
  methods: {
    computedCityOptions() {
      function filterTree(tree, filterArray) {
        return tree
          .filter((node) => !filterArray.includes(node.code)) // 过滤掉在数组中的节点
          .map((node) => {
            // 递归处理子节点
            const filteredChildren = filterTree(
              node.children || [],
              filterArray
            );

            // 构建新的节点对象
            const newNode = {
              ...node,
              // 只有当有子节点时才保留 children 属性
              ...(filteredChildren.length > 0 && {
                children: filteredChildren,
              }),
            };

            return newNode;
          });
      }
      let selectedArray = [];
      for (let item of this.modalData.shippingTemplatesRegionListAppend) {
        console.log(item);

        selectedArray = selectedArray.concat(item.cityCodes);
      }
      console.log("执行", selectedArray);
      console.log(
        "过滤后",
        filterTree(this.$api.mer_admin.getCityOptions(), selectedArray)
      );

      return filterTree(this.$api.mer_admin.getCityOptions(), selectedArray);
    },
    toggle(e) {
      if (this.modalConfig.show == false) {
        this.modalConfig.show = true;
      } else {
        this.modalConfig.show = false;
      }
      if (e) {
        console.log(e);
        this.init(cloneDeep(e.row));
      }
      return {
        add: (item) => {
          console.log(item);
          this.$nextTick(() => {
            this.modalData = JSON.parse(JSON.stringify(BASE_DATA));
          });
          this.isAdd = true;
        },
        update: (row) => {
          this.modalData = row;
          this.isAdd = false;
        },
      };
    },
    init(row) {},
  },
  computed: {
    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 label="按重量">按重量</el-radio>
                <el-radio 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 label="全国包邮">全国包邮</el-radio>
                <el-radio label="自定义运费">自定义运费</el-radio>
              </el-radio-group>
            );
          },
        },
        //自定义运费
        {
          label: "自定义运费配置",
          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);
                    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
                        ref="cityCode"
                        style="width:100%;"
                        v-model={row.cityCodes}
                        onChange={change}
                        options={this.$api.mer_admin.getCityOptions()}
                        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={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: "",
                        //首重
                        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 (
              <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}
                      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
                    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>
            );
          },
        },
        //指定包邮条件
        {
          label: "",
          prop: "",
          type: "jsx-out",
          show: this.modalData.fareConfig == "自定义运费",
          render: () => {
            const tableCols = [
              {
                title: "运送到",
                width: "300px",
                field: "cityCodes",
                type: "jsx",
                render: ({ row }) => {
                  const change = (e) => {
                    console.log(e);
                  };
                  return (
                    <el-cascader
                      style="width:100%;"
                      v-model={row.cityCodes}
                      onChange={change}
                      options={this.$api.mer_admin.getCityOptions()}
                      show-all-levels={false}
                      collapse-tags={true}
                      props={{
                        props: {
                          multiple: true,
                          checkStrictly: false,
                          emitPath: false,
                          label: "name",
                          value: "code",
                        },
                      }}
                      clearable
                      filterable
                    ></el-cascader>
                  );
                },
              },
              {
                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 (
              <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>
            );
          },
        },
      ];
    },
    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: JSON.parse(sessionStorage.getItem("userInfo")).shopId,
                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(",");
                              return item;
                            }
                          )
                        )
                      ),
              });
            }
          }, 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>