<template>
  <div>
    <obj-modal
      ref="modal"
      labelWidth="150px"
      :modalConfig="modalConfig"
      :modalCols="modalCols"
      :modalData="modalData"
      :modalHandles="modalHandles"
    >
      <div slot="dialog__content">
        <el-form :model="modalData" ref="modalForm">
          <obj-table-plus
            style="height: 70vh"
            ref="oTableThree"
            v-model="modalData.levelList"
            :tableCols="tableCols"
            :tableProp="tableProp"
            :toolbarProp="toolbarProp"
            :tableEvent="tableEvent"
          >
            <div slot="tableTop" class="mb-2"></div>
          </obj-table-plus>
        </el-form>
      </div>
    </obj-modal>
    <addCoupon @addCouponData="addCouponData" ref="addCoupon"></addCoupon>
  </div>
</template>
<script>
import addCoupon from "./add-coupon.vue";
import { debounce, cloneDeep } from "lodash";
export default {
  components: { addCoupon },
  data() {
    return {
      isAdd: true,
      isLoading: false,
      //表格属性
      //表格属性
      tableProp: {
        height: "auto",
        border: true,
        "show-overflow": false,
        "auto-resize": false,
        "print-config": {},
      },
      toolbarProp: {},
      tableEvent: {},
      modalConfig: {
        title: "新增等级",
        show: false,
        width: "1300px",
        fullscreen: true,
      },
      modalCols: [],
      couponIndex: 0,
      modalData: {
        marketId: "",
        shopId: "",
        unitType: "",
        levelList: [
          {
            levelName: "",
            requiredGrowthValue: 0,
            growthValueUpperLimit: 999999999,
            enableMemberDiscount: false,
            enablePointsRedemption: false,
            enableBirthdayCoupons: false,
            enableBirthdayReward: false,
            discountRate: "",
            rewardEffectiveTimeType: "",
            memberLevelCouponsList: "",
          },
        ],
      },
    };
  },
  methods: {
    queryTableData(pageNo, pageSize) {
      this.$api.marketing.marketingLevelPage(this.modalData).then((res) => {
        let list = res.data.data ? res.data.data : [];
        this.$refs.oTableThree.complete(list)
      });
      // setTimeout(() => {
      //   setTimeout(() => {
      //     this.$refs.oTableThree.complete([
      //       {
      //         levelName: "",
      //         requiredGrowthValue: 0,
      //         growthValueUpperLimit: 999999999,
      //         enableMemberDiscount: false,
      //         enablePointsRedemption: false,
      //         enableBirthdayCoupons: false,
      //         enableBirthdayReward: false,
      //         discountRate: "",
      //         rewardEffectiveTimeType: "",
      //         memberLevelCouponsList: [],
      //       },
      //     ]);
      //   });
      // }, 10);
    },
    toggle(e) {
      if (this.modalConfig.show == false) {
        this.modalConfig.show = true;
        this.$nextTick(() => {
          this.$refs.oTableThree.doLayout();
        });
      } else {
        this.modalConfig.show = false;
      }
      if (e) {
        this.init(cloneDeep(e.row));
      }
      return {
        add: (row) => {
          console.log(row);

          this.modalData = {
            marketId: row.marketId,
            shopId: row.shopId,
            unitType: row.unitType,
          };
          this.queryTableData();
          this.isAdd = true;
        },
        update: (id) => {
          this.isAdd = false;
        },
      };
    },
    init(row) {
      this.modalData = row;
    },
    addCouponData(data) {
      console.log(data);
      let row = JSON.parse(JSON.stringify(data));
      this.modalData.levelList[this.couponIndex].memberLevelCouponsList = [row];
      this.$refs.modalForm.validate();
    },
  },
  computed: {
    tableCols() {
      return [
        {
          title: "序号",
          type: "seq",
          align: "center",
          width: "60px",
        },
        {
          title: "等级名称",
          field: "typeName",
          align: "center",
          width: "150px",
          type: "jsx",
          render: (e) => {
            let row = e.row;
            return (
              <el-form-item
                prop={`levelList.${e.$rowIndex}.levelName`}
                rules={{
                  required: true,
                  message: "请输入等级名称",
                }}
              >
                <el-input
                  v-model={row.levelName}
                  placeholder="请输入等级名称"
                ></el-input>
              </el-form-item>
            );
          },
        },
        {
          title: "所需成长值",
          field: "requiredGrowthValue",
          align: "center",
          width: "170px",
          type: "jsx",
          render: (e) => {
            let changUpperLimit = () => {
              console.log(
                e.$rowIndex,
                e,
                e.data[e.$rowIndex - 1].growthValueUpperLimit,
                e.data[e.$rowIndex].requiredGrowthValue
              );
              e.data[e.$rowIndex - 1].growthValueUpperLimit =
                e.data[e.$rowIndex].requiredGrowthValue - 1;
            };
            return (
              <el-form-item
                prop={`levelList.${e.$rowIndex}.requiredGrowthValue`}
                rules={{
                  required: true,
                  message: "请输入所需成长值",
                }}
              >
                <el-input-number
                  onChange={changUpperLimit}
                  disabled={e.$rowIndex == 0}
                  style="width:150px"
                  controls-position="right"
                  precision={0}
                  v-model={e.row.requiredGrowthValue}
                  min={0}
                  max={999999999}
                  label="请输入"
                ></el-input-number>
              </el-form-item>
            );
          },
        },
        {
          title: "成长值上限",
          field: "growthValueUpperLimit",
          align: "center",
          width: "170px",
          type: "jsx",
          render: (e) => {
            return (
              <el-form-item
                prop={`levelList.${e.$rowIndex}.requiredGrowthValue`}
                rules={{
                  required: true,
                  message: "请输入所需成长值",
                }}
              >
                <el-input-number
                  disabled={this.modalData.levelList.length == e.$rowIndex + 1}
                  style="width:150px"
                  controls-position="right"
                  precision={0}
                  v-model={e.row.growthValueUpperLimit}
                  min={0}
                  max={999999999}
                  label="请输入"
                ></el-input-number>
              </el-form-item>
            );
          },
        },
        {
          title: "开启会员折扣",
          field: "enableMemberDiscount",
          align: "center",
          width: "120px",
          type: "jsx",
          render: ({ row }) => {
            let changeDiscountRate = () => {
              if (!row.enableMemberDiscount) {
                row.discountRate = "";
              }
            };
            return (
              <el-form-item>
                <el-switch
                  onchange={changeDiscountRate}
                  v-model={row.enableMemberDiscount}
                ></el-switch>
              </el-form-item>
            );
          },
        },
        {
          title: "折扣率（折）",
          field: "discountRate",
          align: "center",
          width: "170px",
          type: "jsx",
          render: (e) => {
            if (e.row.enableMemberDiscount) {
              return (
                <el-form-item
                  prop={`levelList.${e.$rowIndex}.discountRate`}
                  rules={{
                    required: true,
                    message: "请输入所需成长值",
                  }}
                >
                  <el-input-number
                    style="width:150px"
                    controls-position="right"
                    precision={1}
                    v-model={e.row.discountRate}
                    min={0}
                    max={9.9}
                    label="请输入"
                  ></el-input-number>
                </el-form-item>
              );
            } else {
              return <div></div>;
            }
          },
        },
        {
          title: "开启积分兑换",
          field: "enableMemberDiscount",
          align: "center",
          width: "120px",
          type: "jsx",
          render: ({ row }) => {
            return (
              <el-form-item>
                {" "}
                <el-switch
                  v-model={row.enablePointsRedemption}
                ></el-switch>{" "}
              </el-form-item>
            );
          },
        },
        {
          title: "开启生日优惠券",
          field: "enableBirthdayCoupons",
          align: "center",
          width: "120px",
          type: "jsx",
          render: ({ row }) => {
            let changeCouponsList = () => {
              if (!row.enableBirthdayCoupons) {
                row.memberLevelCouponsList = [];
              }
            };
            return (
              <el-form-item>
                <el-switch
                  onchange={changeCouponsList}
                  v-model={row.enableBirthdayCoupons}
                ></el-switch>
              </el-form-item>
            );
          },
        },
        {
          title: "添加生日优惠卷",
          field: "memberLevelCouponsList",
          align: "center",
          width: "150px",
          type: "jsx",
          render: (e) => {
            let addCouponsList = () => {
              this.couponIndex = e.$rowIndex;
              this.$refs.addCoupon.toggle().add(e.row.memberLevelCouponsList);
              console.log(e.row.memberLevelCouponsList);
            };
            if (e.row.enableBirthdayCoupons) {
              return (
                <el-form-item
                  prop={`levelList.${e.$rowIndex}.memberLevelCouponsList`}
                  rules={{
                    required: true,
                    message: "请添加优惠卷",
                  }}
                >
                  <el-button
                    size="mini"
                    onClick={addCouponsList}
                    type="primary"
                  >
                    添加优惠卷
                  </el-button>
                </el-form-item>
              );
            } else {
              return <div></div>;
            }
          },
        },
        {
          title: "开启生日双倍积分",
          field: "enableBirthdayReward",
          align: "center",
          width: "120px",
          type: "jsx",
          render: ({ row }) => {
            let changeReward = () => {
              if (!row.enableBirthdayReward) {
                row.rewardEffectiveTimeType = "";
              }
            };
            return (
              <el-form-item>
                <el-switch
                  onchange={changeReward}
                  v-model={row.enableBirthdayReward}
                ></el-switch>
              </el-form-item>
            );
          },
        },
        {
          title: "双倍积分有效时间",
          field: "rewardEffectiveTimeType",
          align: "center",
          width: "120px",
          type: "jsx",
          render: (e) => {
            if (e.row.enableBirthdayReward) {
              return (
                <el-form-item
                  prop={`levelList.${e.$rowIndex}.rewardEffectiveTimeType`}
                  rules={{
                    required: true,
                    message: "请输入所需成长值",
                  }}
                >
                  <el-select
                    size="mini"
                    v-model={e.row.rewardEffectiveTimeType}
                    placeholder="请选择"
                  >
                    {[
                      { label: "当天", value: "1" },
                      {
                        label: "当月",
                        value: "2",
                      },
                    ].map((item) => {
                      return (
                        <el-option
                          label={item.label}
                          value={item.value}
                        ></el-option>
                      );
                    })}
                  </el-select>
                </el-form-item>
              );
            } else {
              return <div></div>;
            }
          },
        },
        {
          title: "操作",
          fixed: "right",
          type: "jsx",
          width: "200px",
          align: "center",
          render: (e) => {
            let add = () => {
              console.log(e);
              this.modalData.levelList.splice(e.$rowIndex + 1, 0, {
                levelName: "",
                requiredGrowthValue: "0",
                growthValueUpperLimit: "999999999",
                enableMemberDiscount: false,
                enablePointsRedemption: false,
                enableBirthdayCoupons: false,
                enableBirthdayReward: false,
                discountRate: "",
                rewardEffectiveTimeType: "",
                memberLevelCouponsList: [],
              });
            };
            let remove = () => {
              this.modalData.levelList.splice(e.$rowIndex, 1);
            };
            return (
              <div>
                <el-button
                  v-show={this.modalData.levelList.length == e.$rowIndex + 1}
                  style="margin-right: 10px"
                  type="primary"
                  size="mini"
                  onClick={add}
                  slot="reference"
                >
                  添加
                </el-button>
                {this.modalData.levelList.length > 1 && e.$rowIndex != 0 ? (
                  <el-popconfirm title="确认要删除吗？" onConfirm={remove}>
                    <el-button
                      class="ml-1"
                      type="danger"
                      size="mini"
                      slot="reference"
                    >
                      删除
                    </el-button>
                  </el-popconfirm>
                ) : null}
              </div>
            );
          },
        },
      ];
    },
    modalHandles() {
      return [
        {
          label: "取消",
          handle: debounce(() => {
            this.toggle();
          }, 300),
        },
        {
          label: this.isAdd ? "确认添加" : "确认修改",
          type: "primary",
          handle: debounce(() => {
            this.$refs.modalForm.validate((valid) => {
              if (valid) {
                this.$api.marketing
                  .addMarketingLevel(this.modalData)
                  .then((res) => {
                    this.$emit("getList");
                    this.toggle();
                  });
              }
            });
          }, 300),
        },
      ];
    },
  },
  asyncComputed: {},
};
</script>
