<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :rules="rules"
      class="integral-rule-operate"
      :disabled="showViewTime"
      label-width="120px"
    >
      <el-form-item :label="$t('指标类型')" prop="type">
        <dict-selector
          clearable
          :type="DICT_TYPE.SCORE_RULE_TYPE"
          v-model="queryParams.type"
        >
        </dict-selector>
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item :label="$t('中文标题')" prop="titleZh">
            <el-input
              style="width: 300px"
              v-model="queryParams.titleZh"
              :placeholder="$t('请输入查找')"
              clearable
              v-trim
            />
            <el-button
              size="mini"
              type="text"
              style="margin-left: 10px"
              v-if="queryParams.type == '4' && !showViewTime"
              @click="handleSelectBannerDialog()"
              >{{ $t("选择") }}</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('英文标题')" prop="titleEn">
            <el-input
              style="width: 300px"
              v-model="queryParams.titleEn"
              :placeholder="$t('请输入查找')"
              clearable
              v-trim
            /> </el-form-item
        ></el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item :label="$t('中文封面图')" prop="coverImageZh">
            <image-upload v-model="queryParams.coverImageZh" :isShowEditButton="!showViewTime"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('英文封面图')" prop="coverImageEn">
            <image-upload v-model="queryParams.coverImageEn" :isShowEditButton="!showViewTime"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!--分享活动内容 -->
      <el-form-item
        :label="$t('中文活动内容')"
        prop="extraShare.activityDescZh"
        v-if="queryParams.type == '4'"
      >
        <el-col :span="18">
          <editor
            :readOnly="showViewTime"
            :class="{ readOnlyEditor: showViewTime }"
            v-model="queryParams.extraShare.activityDescZh"
            :min-height="150"
          />
        </el-col>
        <el-col :span="1"></el-col>
        <el-button type="text" @click="viewActivityDesc('Zh')">{{
          $t("预览")
        }}</el-button>
      </el-form-item>
      <el-form-item
        :label="$t('英文活动内容')"
        prop="extraShare.activityDescEn"
        v-if="queryParams.type == '4'"
      >
        <el-col :span="18">
          <editor
            :class="{ readOnlyEditor: showViewTime }"
            :readOnly="showViewTime"
            v-model="queryParams.extraShare.activityDescEn"
            :min-height="150"
          />
        </el-col>
        <el-col :span="1"></el-col>
        <el-button type="text" @click="viewActivityDesc('En')">{{
          $t("预览")
        }}</el-button>
      </el-form-item>

      <!-- 链接 -->
      <el-form-item :label="$t('活动链接')" v-if="queryParams.type == '4'" >
        <el-input
          v-model="queryParams.extraShare.activityUrl"
          :placeholder="$t('请输入活动链接')"
          clearable
          :disabled="true"
          onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
        />
      </el-form-item>
      <!-- 推荐分享文案 -->

      <el-row :gutter="10" v-if="queryParams.type == '3'">
        <el-col :span="12">
          <el-form-item
            :label="$t('中文分享文案 ')"
            prop="extraRecommend.shareContentZh"
          >
            <el-input
              type="textarea"
              style="width: 300px"
              v-model="queryParams.extraRecommend.shareContentZh"
              :placeholder="$t('请输入分享文案')"
              clearable
              v-trim
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('英文分享文案')"
            prop="extraRecommend.shareContentEn"
          >
            <el-input
              type="textarea"
              style="width: 300px"
              v-model="queryParams.extraRecommend.shareContentEn"
              :placeholder="$t('请输入分享文案')"
              clearable
              v-trim
            /> </el-form-item
        ></el-col>
      </el-row>
      <!-- 注册链接 -->
      <el-form-item :label="$t('注册链接')" v-if="queryParams.type == '3'">
        <el-input
          v-model="queryParams.registerUrl"
          :placeholder="$t('请输入注册链接')"
          clearable
          :disabled="true"
          onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
        />
      </el-form-item>
      <el-form-item v-if="queryParams.type == '1'" :label="$t('首单')">
        <el-radio-group v-model="queryParams.extraOrderV.firstOrder">
          <el-radio
            v-for="dict in getDictDatas(DICT_TYPE.YES_OR_NO)"
            :key="dict.value"
            :label="dict.value"
            >{{ $l(dict, "label") }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="$t('运输方式')"
        v-if="queryParams.type == '1'"
        prop="extraOrderV.transportType"
      >
        <dict-selector
          clearable
          :type="DICT_TYPE.TRANSPORT_TYPE"
          v-model="queryParams.extraOrderV.transportType"
        >
        </dict-selector>
      </el-form-item>
      <el-form-item
        :label="$t('提货点')"
        v-if="queryParams.type == '1'"
        prop="extraOrderV.receiveAddrList"
      >
        <el-cascader
          v-if="cascaderState"
          style="width: 400px"
          :options="regionTreeList"
          @change="selectHandle"
          @expand-change="selectExpand"
          collapse-tags
          v-model="queryParams.extraOrderV.receiveAddrList"
          :props="cascaderProps"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item
        :label="$t('渠道')"
        v-if="queryParams.extraOrderV.transportType == '3'"
      >
        <el-select v-model="queryParams.channel" multiple placeholder="请选择">
          <el-option
            v-for="item in channelList"
            :key="item.channelId"
            :label="isChinese ? item.nameZh : item.nameEn"
            :value="item.channelId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('积分')" v-if="queryParams.type == '1'" required>
        <el-row
          type="flex"
          justify="start"
          v-for="(item, index) in queryParams.extraOrderV.orderVRule"
        >
          <el-col :span="2">
            <el-form-item
              :prop="'extraOrderV.orderVRule.' + index + '.low'"
              :rules="rules.extraOrderV.orderVRule.low"
            >
              <el-input
                style="width: 100px"
                v-model.number="item.low"
              ></el-input
            ></el-form-item>
          </el-col>
          <el-col :span="1">
            {{ queryParams.extraOrderV.transportType == "3" ? "kg" : "m³" }}
            {{ $t("至") }}
          </el-col>
          <el-col :span="2">
            <el-form-item
              :prop="'extraOrderV.orderVRule.' + index + '.high'"
              :rules="rules.extraOrderV.orderVRule.high"
            >
              <el-input
                style="width: 100px"
                v-model.number="item.high"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="1">
            {{ queryParams.extraOrderV.transportType == "3" ? "kg" : "m³" }} =
          </el-col>
          <el-col :span="2">
            <el-form-item
              :prop="'extraOrderV.orderVRule.' + index + '.score'"
              :rules="rules.extraOrderV.orderVRule.score"
              ><el-input
                style="width: 100px"
                v-model.number="item.score"
              ></el-input
            ></el-form-item>
          </el-col>
          <el-col :span="1">
            {{ $t("积分") }}
          </el-col>
          <el-col :span="1">
            <el-button
              type="primary"
              :icon="index == '0' ? 'el-icon-plus' : 'el-icon-minus'"
              @click="handleOrderVRule(item, index)"
            ></el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <!-- 除v值之外的积分规则 -->
      <el-form-item
        v-if="queryParams.type != '1'"
        :label="$t('积分')"
        prop="getScoreOnce"
      >
        <el-input
          style="width: 300px"
          v-model.number="queryParams.getScoreOnce"
          :placeholder="$t('请输入数字')"
          clearable
          onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
        />
      </el-form-item>
      <el-form-item v-if="queryParams.type != '2'" :label="$t('累计最高积分')">
        <el-input
          style="width: 300px"
          v-model.number="queryParams.maxScoreTotal"
          :placeholder="$t('请输入累计最高积分')"
          clearable
          onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
        />
      </el-form-item>
      <el-form-item
        v-if="queryParams.type == '1'"
        :label="$t('订单入口')"
        prop="extraOrderV.orderEntry"
      >
        <dict-selector
          clearable
          :multiple="true"
          :type="DICT_TYPE.PLATFORM_TYPE"
          v-model="queryParams.extraOrderV.orderEntry"
        >
        </dict-selector>
      </el-form-item>
      <el-form-item
        :label="$t('活动有效期')"
        prop="dateRangeCreateTime"
        :rules="rules.dateRangeCreateTime"
      >
        <el-date-picker
          type="daterange"
          clearable
          placement="bottom-start"
          v-model="queryParams.dateRangeCreateTime"
          style="width: 300px"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="-"
          :start-placeholder="$t('开始日期')"
          :end-placeholder="$t('结束日期')"
        />
      </el-form-item>
      <el-form-item :label="$t('积分有效期')" prop="scorePeriod">
        <el-input
          v-model.number="queryParams.scorePeriod"
          :placeholder="$t('请输入积分有效期天数')"
          clearable
          onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
        />
      </el-form-item>
      <el-form-item :label="$t('排序')" prop="orderNum">
        <el-input
          v-model.number="queryParams.orderNum"
          :placeholder="$t('请输入排序')"
          clearable
          onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
        />
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item :label="$t('中文规则说明')" prop="descZh">
            <el-input type="textarea" v-model="queryParams.descZh"></el-input>
          </el-form-item>
          <span class="del-btn">{{
            $t("注：此说明用于展示给会员查看积分原因，请规范填写")
          }}</span>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('英文规则说明')" prop="descEn">
            <el-input type="textarea" v-model="queryParams.descEn"></el-input>
          </el-form-item>
          <span class="del-btn">{{
            $t("注：此说明用于展示给会员查看积分原因，请规范填写")
          }}</span>
        </el-col>
      </el-row>
      <el-form-item :label="$t('是否推送')" prop="pushActivity">
        <el-radio-group v-model="queryParams.pushActivity">
          <el-radio
            v-for="dict in getDictDatas(DICT_TYPE.YES_OR_NO)"
            :key="dict.value"
            :label="dict.value"
            >{{ $l(dict, "label") }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('展示平台')">
        <dict-selector
          clearable
          formType="checkbox"
          :multiple="true"
          :type="DICT_TYPE.PLATFORM_TYPE"
          v-model="queryParams.showPlatform"
        >
        </dict-selector>
      </el-form-item>
      <el-form-item
        v-if="queryParams.type == '2'"
        :label="$t('注册平台')"
        prop="extraRegister.registerPlatform"
      >
        <dict-selector
          clearable
          :multiple="true"
          :type="DICT_TYPE.CLIENT_PLATFORM"
          v-model="queryParams.extraRegister.registerPlatform"
        >
        </dict-selector>
      </el-form-item>
      <el-form-item
        :label="$t('是否分享')"
        prop="extraRecommend.shareStatus"
        v-if="queryParams.type == '3'"
      >
        <el-radio-group v-model="queryParams.extraRecommend.shareStatus">
          <el-radio
            v-for="dict in getDictDatas(DICT_TYPE.YES_OR_NO)"
            :key="dict.value"
            :label="dict.value"
            >{{ $l(dict, "label") }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="$t('是否分享')"
        prop="extraShare.shareStatus"
        v-if="queryParams.type == '4'"
      >
        <el-radio-group v-model="queryParams.extraShare.shareStatus">
          <el-radio
            v-for="dict in getDictDatas(DICT_TYPE.YES_OR_NO)"
            :key="dict.value"
            :label="dict.value"
            >{{ $l(dict, "label") }}</el-radio
          >
        </el-radio-group>
      </el-form-item>

      <!-- 编辑相关内容 -->
      <div v-if="showViewTime">
        <el-form-item :label="$t('创建人')">
          <el-input
            v-model.number="queryParams.creator"
            :placeholder="$t('请输入创建人')"
            clearable
            onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
          />
        </el-form-item>
        <el-form-item :label="$t('创建时间')">
          <el-date-picker
            type="datetime"
            :placeholder="$t('选择创建时间')"
            v-model="queryParams.createTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placement="bottom-start"
          ></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('最后更新人')">
          <el-input
            
            v-model.number="queryParams.updater"
            :placeholder="$t('请输入最后更新人')"
            clearable
            onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
          />
        </el-form-item>
        <el-form-item :label="$t('最后更新时间')">
          <el-date-picker
            type="datetime"
            :placeholder="$t('选择最后更新时间')"
            v-model="queryParams.updateTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placement="bottom-start"
          ></el-date-picker>
        </el-form-item>
      </div>
    </el-form>
    <el-row justify="end" :gutter="20" type="flex">
      <el-col :span="3" v-if="$route.query.pageStatus == 'new'">
        <el-button
          type="primary"
          @click="handleSaveIntegralRule"
          style="width: 100%"
          >{{ $t("保存") }}</el-button
        >
      </el-col>
      <el-col :span="3" v-if="$route.query.pageStatus == 'new'">
        <el-button
          type="primary"
          style="width: 100%"
          @click="handleEnableIntegralRule"
          >{{ $t("保存并启用") }}</el-button
        >
      </el-col>
      <el-col :span="3" v-if="$route.query.pageStatus == 'edit'">
        <el-button
          type="primary"
          style="width: 100%"
          @click="handleUpdatedIntegralRule"
          >{{ $t("更新") }}</el-button
        >
      </el-col>
      <el-col :span="3">
        <el-button
        v-if="$route.query.pageStatus != 'view'"
          type="primary"
          style="width: 100%"
          @click="handleResetIntegralRule"
          >{{ $t("重置") }}</el-button
        >
      </el-col>

      <el-col :span="3">
        <el-button style="width: 100%" type="primary" @click="handleGoBack">{{
          $t("返回")
        }}</el-button>
      </el-col>
    </el-row>

    <!-- 选择广告弹窗 -->
    <el-dialog
      :title="$t('选择广告')"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-table v-loading="loading" :data="list">
        <el-table-column label="" align="center" prop="id" />
        <el-table-column :label="$t('标题')" align="center" prop="titleZh" />
        <el-table-column
          :label="$t('WEB端图片')"
          align="center"
          prop="bannerUrlWeb"
        >
          <template slot-scope="scope">
            <el-image :src="scope.row.bannerUrlWeb"></el-image>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('APP端图片')"
          align="center"
          prop="bannerUrlApp"
        >
          <template slot-scope="scope">
            <el-image :src="scope.row.bannerUrlApp"></el-image>
          </template>
        </el-table-column>
        <el-table-column :label="$t('状态')" align="center" prop="status">
          <template slot-scope="scope">
            <span>{{ statusName(scope.row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('创建时间')"
          align="center"
          prop="createTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('操作')"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleSelectAdvertising(scope.row)"
              >{{ $t("选择") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-dialog>

    <!-- 预览弹窗 -->
    <el-dialog
      :title="$t('预览')"
      :visible.sync="viewActivityDialog"
      width="400px"
    >
      <div class="container">
        <div class="phoneBox">
          <div class="title">
            {{ reviewDedtails.title }}
          </div>
          <img :src="reviewDedtails.img" alt="" class="coverImg" />
          <div class="detail" v-html="reviewDedtails.detail"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { CommonStatusEnum } from "@/utils/constants";
import { getBannerPage } from "@/api/ecw/banner";
import Editor from "@/components/Editor";
import { getDictDatas, DICT_TYPE } from "@/utils/dict";
import {
  getRegionTreeList,
  getChannelList,
  createIntegralRule,
  integralRuleDetails,
  integralRuleUpdated,
} from "@/api/ecw/memberManagement";
import { deepClone } from "@/utils/index";
import ImageUpload from "@/components/ImageUpload";
import { parseTime } from "@/utils/ruoyi";
import { isNumber } from "min-dash";
import { mergeWith } from "lodash";
export default {
  name: "addIntegrationRuleOperation",
  components: {
    ImageUpload,
    Editor,
  },
  data() {
    const validatePass2 = (rule, value, callback) => {
      const index = Number(rule.field.split(".")[2]);

      if (index == "0") {
        if (
          this.queryParams.extraOrderV.orderVRule[index].low >=
            this.queryParams.extraOrderV.orderVRule[index].high &&
          this.queryParams.extraOrderV.orderVRule[index].high
        ) {
          callback(this.$t("开始积分应小于本次最终积分"));
        } else {
          callback();
        }
      } else if (index > "0") {
        if (
          this.queryParams.extraOrderV.orderVRule[index].low >=
            this.queryParams.extraOrderV.orderVRule[index].high &&
          this.queryParams.extraOrderV.orderVRule[index].high
        ) {
          callback(this.$t("开始积分应小于本次最终积分"));
        } else if (
          this.queryParams.extraOrderV.orderVRule[index].low <=
          this.queryParams.extraOrderV.orderVRule[index - 1].high
        ) {
          callback(this.$t("开始积分应大于上一次最终积分"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validatehigh = (rule, value, callback) => {
      const index = Number(rule.field.split(".")[2]);
      if (index == "0") {
        if (
          this.queryParams.extraOrderV.orderVRule[index].low &&
          this.queryParams.extraOrderV.orderVRule[index].low >=
            this.queryParams.extraOrderV.orderVRule[index].high
        ) {
          callback(this.$t("本次最终积分应大于本次开始积分"));
        } else if (
          this.queryParams.extraOrderV.orderVRule[index + 1] &&
          this.queryParams.extraOrderV.orderVRule[index + 1].low &&
          this.queryParams.extraOrderV.orderVRule[index + 1].low <=
            this.queryParams.extraOrderV.orderVRule[index].high
        ) {
          callback(this.$t("本次最终积分应小于下一次开始积分"));
        } else {
          callback();
        }
      } else if (index > 0) {
        if (
          this.queryParams.extraOrderV.orderVRule[index].low &&
          this.queryParams.extraOrderV.orderVRule[index].low >=
            this.queryParams.extraOrderV.orderVRule[index].high
        ) {
          callback(this.$t("本次最终积分应大于本次开始积分"));
        } else if (
          this.queryParams.extraOrderV.orderVRule[index + 1]?.low &&
          this.queryParams.extraOrderV.orderVRule[index].high <=
            this.queryParams.extraOrderV.orderVRule[index + 1].low
        ) {
          callback(this.$t("本次最终积分应小于下一次开始积分"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      viewActivityDialog: false,
      //查看显示时间详情
      showViewTime: false,
      CommonStatusEnum: CommonStatusEnum,
      statusDictDatas: getDictDatas(DICT_TYPE.COMMON_STATUS),
      loading: true,
      total: 0,
      // 广告设置列表
      list: [],
      queryadvertisingParams: {
        pageNo: 1,
        pageSize: 10,
        titleZh: null,
        titleEn: null,
        contentZh: null,
        contentEn: null,
        bannerUrlWeb: null,
        bannerUrlApp: null,
        status: null,
      },
      cascaderState: true,
      channelList: [],
      regionTreeList: [],
      dialogVisible: false,
      rules: {
        pushActivity: [
          {
            required: true,
            message: this.$t("请选择是否推送"),
            trigger: "change",
          },
        ],
        getScoreOnce: [
          {
            required: true,
            message: this.$t("请输入积分"),
            trigger: "blur",
          },
          {
            type: "number",
            message: this.$t("请输入整数"),
            trigger: "blur",
          },
        ],
        descEn: [
          {
            required: true,
            message: this.$t("请输入英文规则说明"),
            trigger: "blur",
          },
        ],
        descZh: [
          {
            required: true,
            message: this.$t("请输入中文规则说明"),
            trigger: "blur",
          },
        ],
        titleZh: [
          {
            required: true,
            message: this.$t("请输入中文标题"),
            trigger: "blur",
          },
        ],
        titleEn: [
          {
            required: true,
            message: this.$t("请输入中文标题"),
            trigger: "blur",
          },
        ],
        orderNum: [
          {
            required: true,
            message: this.$t("请输入排序"),
            trigger: "blur",
          },
          {
            type: "number",
            message: this.$t("请输入整数"),
            trigger: "blur",
          },
        ],
        scorePeriod: [
          {
            type: "number",
            message: this.$t("请输入整数"),
            trigger: "blur",
          },
          {
            required: true,
            message: this.$t("请输入积分有效天数"),
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: this.$t("请选择指标类型"),
            trigger: "change",
          },
        ],
        dateRangeCreateTime: [
          {
            required: true,
            message: this.$t("请选择活动有效期"),
            trigger: "change",
          },
        ],
        //推荐
        extraRecommend: {
          shareContentEn: [
            {
              required: true,
              message: this.$t("请输入分享文案"),
              trigger: "blur",
            },
          ],
          shareContentZh: [
            {
              required: true,
              message: this.$t("请输入分享文案"),
              trigger: "blur",
            },
          ],
          shareStatus: [
            {
              required: true,
              message: this.$t("请选择是否分享"),
              trigger: "change",
            },
          ],
        },
        //v值
        extraOrderV: {
          orderEntry: [
            { required: true, message: "请选择订单入口", trigger: "change" },
          ],
          transportType: [
            { required: true, message: "请选择运输方式", trigger: "change" },
          ],
          receiveAddrList: [
            { required: true, message: "请选择提货点", trigger: "change" },
          ],
          orderVRule: {
            low: [
              {
                required: true,
                message: this.$t("不能为空"),
                trigger: "blur",
              },
              {
                type: "number",
                message: this.$t("请输入整数"),
                trigger: "blur",
              },
              { validator: validatePass2, trigger: "blur" },
            ],
            score: [
              {
                required: true,
                message: this.$t("不能为空"),
                trigger: "blur",
              },
              {
                type: "number",
                message: this.$t("请输入整数"),
                trigger: "blur",
              },
            ],
            high: [
              {
                required: true,
                message: this.$t("不能为空"),
                trigger: "blur",
              },
              {
                type: "number",
                message: this.$t("请输入整数"),
                trigger: "blur",
              },
              { validator: validatehigh, trigger: "blur" },
            ],
          },
        },
        //注册
        extraRegister: {
          registerPlatform: [
            {
              required: true,
              message: this.$t("请选择注册平台"),
              trigger: "change",
            },
          ],
        },
        //分享
        extraShare: {
          activityDescEn: [
            {
              required: true,
              message: this.$t("中文活动内容不能为空"),
              trigger: "blur",
            },
          ],
          activityDescZh: [
            {
              required: true,
              message: this.$t("英文活动内容不能为空"),
              trigger: "blur",
            },
          ],
          shareStatus: [
            {
              required: true,
              message: this.$t("请选择是否分享"),
              trigger: "change",
            },
          ],
        },
      },
      lastSelectedList: [], //上一次选中数据
      oneDimensionalList: [],
      reviewDedtails: {},
      queryParams: {
        dateRangeCreateTime: [], //活动有效期
        type: "", //指标类型
        titleZh: "",
        titleEn: "",
        coverImageZh: "",
        coverImageEn: "",
        maxScoreTotal: "",
        endTime: "",
        startTime: "", //活动开始时间
        scorePeriod: "", //积分有效期
        orderNum: "", //排序
        descZh: "",
        pushActivity: "0", //是否推送（0是，1否）默认是
        descEn: "",
        getScoreOnce: "", //除v值之外的积分规则
        showPlatform: "1,2,3", //展示平台
        registerUrl: "", //注册链接
        extraRecommend: {
          //推荐
          shareContentEn: "",
          shareContentZh: "",
          shareStatus: "0", //是否分享（0是，1否）默认是
        },
        extraRegister: {
          //	注册扩展字段
          registerPlatform: null,
        },
        extraOrderV: {
          //订单V值扩展字段
          firstOrder: "1",
          orderEntry: null,
          transportType: "", //运输方式
          receiveAddrList: [],
          orderVRule: [{ low: "", high: "", score: "" }],
        },
        extraShare: {
          //	分享扩展字段
          activityDescEn: null,
          activityDescZh: null,
          activityUrl: "",
          shareStatus: "0",
        },
      },
    };
  },
  computed: {
    statusName() {
      return (value) => {
        for (let index in this.statusDictDatas) {
          let dictItem = this.statusDictDatas[index];
          if (dictItem.value == value) {
            return dictItem.value == CommonStatusEnum.ENABLE + ""
              ? this.$t("正常")
              : this.$t("禁用");
          }
        }
      };
    },
    isChinese() {
      return this.$i18n.locale === "zh_CN";
    },
    cascaderProps() {
      const label = this.isChinese ? "labelZh" : "labelEn";
      return { multiple: true, value: "id", label };
    },
  },
  watch: {
    "queryParams.dateRangeCreateTime": {
      handler: function (newVal, oldVal) {
        this.$nextTick(() => {
          if (newVal.length) {
            this.queryParams.startTime = newVal[0];
            this.queryParams.endTime = newVal[1];
          } else {
            this.queryParams.startTime = "";
            this.queryParams.endTime = "";
          }
        });
      },
      immediate: true,
    },
    isChinese: {
      handler: function (newVal, oldVal) {
        this.cascaderState = false;
        this.$nextTick(() => {
          this.cascaderState = true;
        });
      },
      immediate: true,
    },
  },
  created() {
    this.handleGetChannelList();
    this.queryParams.registerUrl =
      process.env.VUE_APP_BASE_API + "/#/pages/register/register";
    this.getList();
    if (this.$route.query.pageStatus == "edit") {
      this.handleIntegralRuleDetails();
    } else if (this.$route.query.pageStatus == "view") {
      this.showViewTime = true;
      this.handleIntegralRuleDetails();
    } else {
      this.handleGetRegionTreeList();
    }
    this.queryParams.extraShare.activityUrl = '/pages/activityShare/index'
  },
  activated() {},
  methods: {
    //process.env.NODE_ENV
    //预览活动详情
    viewActivityDesc(val) {
      this.viewActivityDialog = true;
      this.reviewDedtails.title = this.queryParams[`title${val}`];
      this.reviewDedtails.img = this.queryParams[`coverImage${val}`];
      this.reviewDedtails.detail =
        this.queryParams.extraShare[`activityDesc${val}`];
      console.log("ppp", this.queryParams);
      console.log("eeeppp", this.reviewDedtails);
    },
    //编辑更新积分规则
    handleUpdatedIntegralRule() {
      this.$refs["queryForm"].validate((valid) => {
        if (valid) {
          let params = deepClone(this.queryParams);
          params.showPlatform = this.queryParams.showPlatform?.join();
          params.extraOrderV.orderEntry =
            this.queryParams.extraOrderV?.orderEntry?.join();
          params.extraRegister.registerPlatform =
            this.queryParams.extraRegister.registerPlatform?.join();
          if (
            (this.queryParams.type ==
              1 &&
              this.queryParams.extraOrderV.receiveAddrList?.[0]?.[0] == "000")
          ) {
            // params.extraOrderV.receiveAddrList[0] = [0, 0, 0];
            params.extraOrderV.receiveAddrList = [[0, 0, 0]];
          }
          integralRuleUpdated(params).then((res) => {
            this.$message.success(this.$t("更新成功"));
            this.$router.go(-1);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //获取积分规则详情
    handleIntegralRuleDetails() {
      this.queryParams.showPlatform = [];
      integralRuleDetails({ id: this.$route.query.id }).then((res) => {
        const params = mergeWith(
          deepClone(this.queryParams),
          res.data,
          (a, b) => {
            return b === null ? a : undefined;
          }
        );

        params.createTime = parseTime(res.data.createTime, '{y}-{m}-{d} {h}:{i}:{s}');
        params.updateTime = parseTime(res.data.updateTime, '{y}-{m}-{d} {h}:{i}:{s}');

        if (isNumber(res.data.extraOrderV?.firstOrder)) {
          params.extraOrderV.firstOrder =
            res.data.extraOrderV?.firstOrder.toString();
        }
        if (isNumber(res.data.pushActivity)) {
          params.pushActivity = res.data.pushActivity.toString();
        }
        if (isNumber(res.data.extraShare?.shareStatus)) {
          params.extraShare.shareStatus =
            params.extraShare.shareStatus.toString();
        }
        if (isNumber(res.data.extraRecommend?.shareStatus)) {
          params.extraRecommend.shareStatus =
            res.data.extraRecommend?.shareStatus.toString();
        }
        console.log(params);
        params.dateRangeCreateTime = [
          parseTime(res.data.startTime),
          parseTime(res.data.endTime),
        ];

        if (
          params.type == 1 &&
          params.extraOrderV.receiveAddrList[0].toString() == "0,0,0"
        ) {
          params.extraOrderV.receiveAddrList = [["000"]];
        }
        this.queryParams = { ...params };
        this.handleGetRegionTreeList();
      });
    },
    handleSelectBannerDialog() {
      this.dialogVisible = true;
    },
    handleSelectAdvertising(row) {
      this.dialogVisible = false;
      this.queryParams.titleZh = row.titleZh;
      this.queryParams.titleEn = row.titleEn;
      this.queryParams.coverImageZh = row.bannerUrlApp;
      this.queryParams.coverImageEn = row.bannerUrlApp;
      this.queryParams.extraShare.activityDescZh = row.contentEn;
      this.queryParams.extraShare.activityDescEn = row.contentZh;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = { ...this.queryadvertisingParams };
      getBannerPage(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    //重置按钮操作
    handleResetIntegralRule() {
      this.$modal
        .confirm(this.$t("是否确认重置此礼品规则表单"), this.$t("提示"))
        .then(() => {
          this.$refs["queryForm"].resetFields();
          this.$modal.msgSuccess(this.$t("重置成功"));
        })
        .catch(() => {});
    },
    //返回按钮操作
    handleGoBack() {
      this.$modal
        .confirm(this.$t("是否确认返回"), this.$t("提示"))
        .then(() => {
          // this.$router.go(-1);
          this.$store.dispatch("tagsView/delCurrentView");
          this.$modal.msgSuccess(this.$t("成功"));
        })
        .catch(() => {});
    },
    //保存
    handleSaveIntegralRule() {
      this.$refs["queryForm"].validate((valid) => {
        if (valid) {
          let params = deepClone(this.queryParams);
          params.showPlatform = this.queryParams.showPlatform?.join();
          params.extraOrderV.orderEntry =
            this.queryParams.extraOrderV?.orderEntry?.join();
          params.extraRegister.registerPlatform =
            this.queryParams.extraRegister.registerPlatform?.join();
          params.status = this.queryParams.status || "2";
          if (
            (this.queryParams.type ==
              1 && this.queryParams.extraOrderV.receiveAddrList[0][0] == "000")
          ) {
            params.extraOrderV.receiveAddrList = [[0, 0, 0]];
          }
          createIntegralRule(params).then((res) => {
            this.$message.success(this.$t("成功"));
            this.$router.go(-1);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //保存并启用
    handleEnableIntegralRule() {
      this.$refs["queryForm"].validate((valid) => {
        if (valid) {
          let params = deepClone(this.queryParams);
          params.showPlatform = this.queryParams.showPlatform?.join();
          params.extraOrderV.orderEntry =
            this.queryParams.extraOrderV.orderEntry?.join();
          params.extraRegister.registerPlatform =
            this.queryParams.extraRegister.registerPlatform?.join();
          params.status = this.queryParams.status || "1";
          if (
            (this.queryParams.type ==
              1 && this.queryParams.extraOrderV.receiveAddrList[0][0] == "000")
          ) {
            params.extraOrderV.receiveAddrList = [[0, 0, 0]];
          }
          createIntegralRule(params).then((res) => {
            this.$message.success(this.$t("成功"));
            this.$router.go(-1);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleOrderVRule(item, index) {
      if (index == "0") {
        this.queryParams.extraOrderV.orderVRule.push({
          low: "",
          high: "",
          score: "",
        });
      } else {
        this.queryParams.extraOrderV.orderVRule.splice(index, 1);
      }
    },
    //获取渠道列表
    handleGetChannelList() {
      getChannelList().then((res) => {
        this.channelList = res.data;
      });
    },
    selectExpand(val) {
      console.log("PPPPPPP", val);
    },
    selectHandle(val, defaultStatus = false) {
      this.queryParams.extraOrderV.receiveAddrList = [];
      let current = []; // 获取当前选中的哪个数据
      if (val.length >= this.lastSelectedList.length) {
        let keys = this.lastSelectedList.map((item) => JSON.stringify(item));
        current = val.filter((item) => !keys.includes(JSON.stringify(item)));
      } else {
        // 取消选中
        let keys = val.map((item) => JSON.stringify(item));
        current = this.lastSelectedList.filter(
          (item) => !keys.includes(JSON.stringify(item))
        );
      }

      const currentValue = current.length > 0 ? current[0][0] || "" : "";
      if (currentValue == "000") {
        if (this.judgetAllSelected(val)) {
          this.traverseTree(this.regionTreeList); //获取全选时回显的数据
        } else {
          this.queryParams.extraOrderV.receiveAddrList = []; //不选
        }
      } else {
        this.queryParams.extraOrderV.receiveAddrList = val; //半选
      }
      if (!defaultStatus) {
        this.checkIsAddAllSelected();
      }

      // this.$nextTick(() => {
      //
      this.lastSelectedList = this.queryParams.extraOrderV.receiveAddrList;
      // });
    },
    checkIsAddAllSelected() {
      //这里你要判断好你的dom是否正确
      let label1 = document
        .querySelectorAll(".el-cascader-panel")[0]
        .querySelector(".el-cascader-menu__wrap")
        .querySelectorAll("li")[0]
        .querySelectorAll("label")[0];
      let span1 = document
        .querySelectorAll(".el-cascader-panel")[0]
        .querySelector(".el-cascader-menu__wrap")
        .querySelectorAll("li")[0]
        .querySelectorAll("label")[0]
        .querySelectorAll("span")[0];
      // 获取所有的数据
      let list = this.regionTreeList; // 原始数据列表
      if (this.oneDimensionalList.length === 0) {
        this.getTreeList(list); // 把所有的父子级平铺成一个一级列表
      }

      let origin = [...this.oneDimensionalList].filter(
        (item) => !item.children
      ); //获取所有的叶子节点
      let nowList = [...this.queryParams.extraOrderV.receiveAddrList].filter(
        (item) => item[0] !== "000"
      );

      // 半选时, 如果有之前选过全选,要把全选过滤掉
      if (origin.length > nowList.length && nowList.length != 0) {
        this.queryParams.extraOrderV.receiveAddrList = deepClone(
          this.queryParams.extraOrderV.receiveAddrList.filter(
            (item) => item[0] !== "000"
          )
        );
        //设置半选样式，setTimeout可以解决样式渲染不上的问题
        setTimeout(function () {
          label1.className = "el-checkbox";
          span1.className = "el-checkbox__input is-indeterminate";
        }, 1);
      } else if (nowList.length == 0) {
        //不选时, 如果有之前选过全选,要把全选过滤掉
        this.queryParams.extraOrderV.receiveAddrList = deepClone(
          this.queryParams.extraOrderV.receiveAddrList.filter(
            (item) => item[0] !== "000"
          )
        );
        label1.className = "el-checkbox";
        span1.className = "el-checkbox__input";
      } else {
        // 当所有的数据都选择时, 要自动把全选勾选上  最后这种是：origin.length == nowList.length
        if (
          this.queryParams.extraOrderV.receiveAddrList[0] &&
          this.queryParams.extraOrderV.receiveAddrList[0][0] !== "000"
        ) {
          this.queryParams.extraOrderV.receiveAddrList = [
            ["000"],
            ...this.queryParams.extraOrderV.receiveAddrList,
          ];
          label1.className = "el-checkbox";
          span1.className = "el-checkbox__input is-checked";
        }
      }
    },
    getTreeList(list) {
      let _this = this;
      for (let i = 0; i < list.length; i++) {
        let a = list[i];
        if (a.id !== "000") {
          this.oneDimensionalList.push(list[i]);
        }
        if (a.children && a.children.length > 0) {
          let res = _this.getTreeList(a.children);
          if (res) {
            return res;
          }
        }
      }
    },
    judgetAllSelected(node) {
      // 判断是否是全选,也就是看已选择的选中中包不包含"全选"
      let isAllSelected = false;
      for (let i = 0; i < node.length; i++) {
        if (node[i][0] == "000") {
          isAllSelected = true;
          break;
        }
      }
      return isAllSelected;
    },
    traverseTree(list, parentNode = []) {
      list.length > 0 &&
        list.forEach((e) => {
          let pNode = deepClone(parentNode);
          if (e.children && e.children.length > 0) {
            pNode.push(e.id); // 1 11
            this.traverseTree(e.children, pNode);
          } else {
            if (parentNode.length > 0) {
              this.queryParams.extraOrderV.receiveAddrList.push([
                ...parentNode,
                e.id,
              ]);
            } else {
              this.queryParams.extraOrderV.receiveAddrList.push([e.id]);
            }
          }
        });
    },
    //获取目的仓列表
    handleGetRegionTreeList() {
      getRegionTreeList().then((res) => {
        this.regionTreeList = res.data;
        this.regionTreeList.unshift({
          id: "000",
          labelZh: "全选",
          labelEn: "select ALL",
        });
        this.$nextTick(() => {
          this.selectHandle(this.queryParams.extraOrderV.receiveAddrList, true);
        });
      });
    },

    //积分来源
    handleSourceType(id) {
      return this.getDictDatas(DICT_TYPE.SCORE_RULE_TYPE).filter(
        (item) => item.value == id
      )[0];
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .integral-rule-operate .el-input {
  width: 300px;
}
.del-btn {
  color: red;
  padding-left: 120px;
}
.readOnlyEditor {
  background-color: #f5f7fa;
  cursor: not-allowed;
}
.phoneBox {
  width: 375px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.container {
  display: flex;
  justify-items: center;
}
.coverImg {
  height: auto;
  width: 100%;
}
</style>
