<template>
  <div>
    <el-container>
      <el-main>
        <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
          <el-divider content-position="left">策略基本信息</el-divider>
          <el-row :gutter="10">
            <el-col :span="17">
              <el-form-item label="策略名称" prop="strategyName">
                <el-input style="width: 300px" v-model="form.strategyName" />
              </el-form-item>
              <el-form-item label="策略类型" prop="strategyType">
                <el-select style="width: 300px" v-model="form.strategyType" placeholder="请选择策略类型">
                  <el-option label="基本策略" :value="0" />
                  <el-option label="活动策略" :value="1" />
                  <el-option label="测试策略" :value="2" />
                </el-select>
              </el-form-item>
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-form-item label="使用模板" prop="templateId">
                    <el-select v-model="form.templateId" style="width: 300px" clearable placeholder="请选择模板">
                      <el-option v-for="item in templateList" :key="item.id" :label="item.templateName" :value="item.id">
                        <span style="float: left; margin-right: 10px">{{
                          item.templateName
                        }}</span>
                        <el-popover placement="right" trigger="hover">
                          <img :src="item.templatePhoto" width="400" />
                          <img slot="reference" :src="item.templatePhoto" width="30" height="30" style="float: right" />
                        </el-popover>
                      </el-option>
                    </el-select>
                    <div style="width:300px;font-size:10px;line-height: 20px;">聚合及炫彩聚合模板，暂不建议使用“简单认证-升级及短信认证-升级”</div>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="产品适配" multiple>
                    <el-select v-model="extJson.dispose" style="width: 300px" clearable placeholder="客户端适配">
                      <el-option v-for="item in disposeList" :key="item.value" :label="item.label" :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-form-item label="认证方式">
                    <el-select style="width: 300px" v-model="extJson.attestation" placeholder="请选择认证方式">
                      <el-option label="统一认证-升级" :value="3">
                        <span style="float:left">统一认证-升级</span>
                        <span style="float:right;color:#F56C6C">推荐</span>
                      </el-option>
                      <el-option label="短信认证-升级" :value="4">
                        <span style="float:left">短信认证-升级</span>
                        <span style="float:right;color:#F56C6C">推荐</span>
                      </el-option>
                      <el-option label="简单认证-升级" :value="5">
                        <span style="float:left">简单认证-升级</span>
                        <span style="float:right;color:#F56C6C">推荐</span>
                      </el-option>
                      <el-option label="统一认证" :value="0" />
                      <el-option label="短信认证" :value="1" />
                      <el-option label="简单认证" :value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="信息回传方式">
                    <el-select style="width: 300px" v-model="extJson.returnApi" placeholder="请选择回传方式">
                      <el-option label="点击订购" value="0" />
                      <el-option label="订购成功/超时" value="1" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="10">
                  <el-form-item label="主产品">
                    <el-select filterable v-model="form.primaryProductId" style="width: 300px" placeholder="请选择策略主产品">
                      <el-option v-for="item in productInfoList" :key="item.id" :label="`${item.productName}/${item.remark}/${item.spid}`" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="副产品">
                    <el-select filterable v-model="form.viceProductIds" style="width: 300px" multiple placeholder="请选择策略副产品">
                      <el-option v-for="(item, index) in productInfoList" :key="item.id" :label="`${item.productName}/${item.remark}/${item.spid}`" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="20">
                  <el-form-item label="策略备注" prop="maskText">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="form.maskText" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="有效性">
                <el-switch style="width: 300px" v-model="form.strategyStatus" active-text="生效中" inactive-text="未生效" active-value="1" inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left">策略配置 </el-divider>
          <el-row :gutter="10">
            <el-col :span="17">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="隐私声明">
                    <el-switch style="width: 300px" v-model="extJson.privacy" active-text="勾选" inactive-text="不勾选" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item label="附加声明">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="extJson.privacyText" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="合约退订">
                    <el-switch style="width: 300px" v-model="extJson.treaty" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item label="提示文案">
                    <el-input type="textarea" placeholder="不填写则默认为：合约期外退订无需缴纳违约金，合约期内退订需一次性支付违约金话费xxx元，是否退订" :autosize="{ minRows: 2, maxRows: 4 }" v-model="extJson.treatyText" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="启用遮罩">
                    <el-switch style="width: 300px" v-model="extJson.isMask" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item label="遮罩文本">
                    <el-row :gutter="24">
                      <el-col :span="11" style="padding: 0 !important">
                        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="extJson.maskText" />
                      </el-col>
                      <el-col :span="11">
                        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="extJson.maskText2" />
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item>
                    <!-- <el-switch style="width: 300px" v-model="extJson.isMask" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" /> -->
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item label="副产品文本">
                    <el-row :gutter="24">
                      <el-col :span="11" style="padding: 0 !important">
                        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="extJson.fitText" />
                      </el-col>
                      <el-col :span="11">
                        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="extJson.fitText2" />
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="订购按钮">
                    <el-switch style="width: 300px" v-model="extJson.isBuy" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="主产品文案">
                    <el-input type="text" v-model="extJson.btnText" />
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="副产品文案" label-width="120px">
                    <el-input type="text" v-model="extJson.btnTextAss" />
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="启用走马灯">
                    <el-switch style="width: 300px" v-model="extJson.isZoetrope" active-text="启用" inactive-text="不启用"
                      active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="18">
                  <el-form-item label="走马灯文本">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="extJson.zoetropeText" />
                  </el-form-item>
                </el-col>
              </el-row> -->
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="订购记录">
                    <el-switch style="width: 300px" v-model="extJson.jiluBtn" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="流量激活">
                    <el-switch style="width: 300px" v-model="extJson.jihuoBtn" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="会员领取">
                    <el-switch style="width: 300px" v-model="extJson.memberBtn" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="一键反馈">
                    <el-switch v-model="extJson.guanzhuBtn" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="退订产品">
                    <el-switch style="width: 300px" v-model="extJson.tuidingBtn" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="流量查询">
                    <el-switch style="width: 300px" v-model="extJson.chaxunBtn" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="启用直充">
                    <el-switch style="width: 300px" v-model="extJson.isZhic" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-tooltip content="配置客户端激活则自动调用，无则自动跳转“激活指引”页面" placement="top" effect="light">
                    <el-form-item label="自动激活">
                      <el-switch style="width: 300px" v-model="extJson.activation" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                    </el-form-item>
                  </el-tooltip>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="营销事件">
                    <el-switch style="width: 300px" v-model="extJson.extendVal" active-text="启用" inactive-text="不启用" active-value="1" inactive-value="0" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="13">
                  <el-form-item label="订购人数">
                    <el-row :gutter="24">
                      <el-col :span="5">
                        <el-input type="text" v-model="extJson.orderNum" placeholder="初始值" />
                      </el-col>
                      <el-col :span="4">
                        <el-input type="text" v-model="extJson.orderAdd" placeholder="步幅" />
                      </el-col>
                      <el-col :span="14">
                        <el-input type="text" v-model="extJson.orderText" placeholder="默认:用户已抢购成功" />
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="13">
                  <el-form-item label="退订弹窗文案">
                    <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 4 }" v-model="extJson.unBuyText" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="推荐策略">
                <el-select v-model="form.recommendStrategyIds" multiple filterable placeholder="请选择">
                  <el-option v-for="(item, index) in strategyInfoNewList" :key="index" :label="item.strategyName" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="退订引流">
                <el-select clearable v-model="form.unsubscribeStrategyIds[0]" filterable placeholder="请选择">
                  <el-option v-for="(item, index) in strategyInfoNewList" :key="index" :label="item.strategyName" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="重复订购引流">
                <el-select clearable v-model="extJson.orderRepeat" filterable placeholder="请选择">
                  <el-option v-for="(item, index) in strategyInfoNewList" :key="index" :label="item.strategyName" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="营销配图">
                <el-upload class="avatar-uploader" :action="imgapi" :show-file-list="false" :on-success="extendImgSuccess">
                  <div v-if="extJson.extendImg">
                    <img style="float: left" :src="extJson.extendImg" class="avatar" />
                  </div>
                  <el-button v-else size="small" type="primary">
                    点击上传
                  </el-button>
                </el-upload>
                <div v-if="extJson.extendImg" style="
                    display: inline-block;
                    color: #20a0ff;
                    padding-left: 20px;
                  " @click="extJson.extendImg = ''">
                  删除
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left">外链活动 </el-divider>
          <el-row :gutter="10">
            <el-col :span="17">
              <el-row :gutter="20">
                <el-col :span="20">
                  <el-form-item label="活动链接">
                    <el-input type="text" v-model="form.linkUrl" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="活动类别">
                <el-select v-model="form.activityType" placeholder="请选择策略主产品">
                  <el-option label="无活动" :value="0" />
                  <el-option label="科创活动" :value="1" />
                  <el-option label="铂原活动" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="活动ID">
                <el-select v-model="form.activityUuid" placeholder="当前策略涉及活动的id（由数据分析平台提供）">
                  <el-option label="基本策略" :value="0" />
                  <el-option label="活动策略" :value="1" />
                </el-select>
              </el-form-item>

              <el-form-item label="活动海报">
                <el-upload class="avatar-uploader" :action="imgapi" :show-file-list="false" :on-success="changePromotionPicposterPhoto">
                  <div v-if="form.posterPhoto">
                    <img style="float: left" :src="form.posterPhoto" class="avatar" />
                  </div>
                  <el-button v-else size="small" type="primary">
                    点击上传
                  </el-button>
                </el-upload>
                <div v-if="form.posterPhoto" style="
                    display: inline-block;
                    color: #20a0ff;
                    padding-left: 20px;
                  " @click="form.posterPhoto = ''">
                  删除
                </div>
              </el-form-item>
              <el-form-item label="活动logo">
                <el-upload class="avatar-uploader" :action="imgapi" :show-file-list="false" :on-success="changePromotionPicactivityLogo">
                  <div v-if="form.activityLogo">
                    <img style="float: left" :src="form.activityLogo" class="avatar" />
                  </div>
                  <el-button v-else size="small" type="primary">
                    点击上传
                  </el-button>
                </el-upload>
                <div v-if="form.activityLogo" style="
                    display: inline-block;
                    color: #20a0ff;
                    padding-left: 20px;
                  " @click="form.activityLogo = ''">
                  删除
                </div>
              </el-form-item>
              <el-form-item label="推广图">
                <el-upload class="avatar-uploader" :action="imgapi" :show-file-list="false" :on-success="changePromotionPicpromotePhoto">
                  <div v-if="form.promotePhoto">
                    <img style="float: left" :src="form.promotePhoto" class="avatar" />
                  </div>
                  <el-button v-else size="small" type="primary">
                    点击上传
                  </el-button>
                </el-upload>
                <div v-if="form.promotePhoto" style="
                    display: inline-block;
                    color: #20a0ff;
                    padding-left: 20px;
                  " @click="form.promotePhoto = ''">
                  删除
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-divider v-if="form.strategyType === 1" content-position="left">策略匹配</el-divider>
        <el-form v-if="form.strategyType === 1" ref="form" :model="rulesform" label-width="80px">
          <el-form-item label="渠道选择">
            <el-cascader v-model="checkedchannel" :options="options" :props="props" show-all-levels clearable filterable>
            </el-cascader>
          </el-form-item>
          <el-form-item label="日期选择">
            <el-date-picker type="datetimerange" clearable v-model="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至" value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="星期选择">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">
              全选
            </el-checkbox>
            <div style="margin: 15px 0"></div>
            <el-checkbox-group v-model="checkedWeeks" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="item in weeksList" :label="item" :key="item">{{ item }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="时间选择">
            <el-time-picker v-model="rulesform.activeStartTime" :picker-options="{
                start: '00:00',
                end: '18:30',
              }" format="HH:mm:ss" value-format="HH:mm:ss" placeholder="开始时间">
            </el-time-picker>
            -
            <el-time-picker v-model="rulesform.activeEndTime" format="HH:mm:ss" value-format="HH:mm:ss" placeholder="结束时间">
            </el-time-picker>
          </el-form-item>
        </el-form>
      </el-main>
      <el-footer>
        <div class="bodyBox">
          <div style="display: flex; justify-content: flex-end">
            <el-button type="primary" @click="onSubmit('ruleForm')">
              {{ btn }}
            </el-button>
            <el-button @click="close"> 取消 </el-button>
          </div>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
function getArrayClassification (params) {
  var options = {
    data: params.data,
    parent: params.parent,
    id: params.id,
    child: params.child,
  };
  let tree = options.data.filter(function (parent) {
    let item = options.data.filter(function (child) {
      return parent[options.id] == child[options.parent];
    });
    if (item.length > 0) {
      parent[options.child] = item;
    }
    return parent[options.parent] == 0;
  });
  return tree;
}

import { post, get } from "@/api/common";

const XEUtils = require("xe-utils");
const weekOptions = ["周日", "周一", "周二 ", "周三", "周四", "周五", "周六"];
export default {
  name: "SchemeAdd",
  data () {
    return {
      // 图片上传api
      imgapi: process.env.VUE_APP_BASE_IMG_API,
      //模版列表
      templateList: [],
      //产品列表
      productInfoList: [],
      //策略列表
      strategyInfoNewList: [],
      //策略匹配
      activeNames: ["1"],
      datetimerange: [],
      timerange: [],
      checkAll: false,
      weeksList: weekOptions,
      isIndeterminate: true,
      checkedWeeks: [],
      //渠道选择
      props: {
        multiple: true,
      },
      options: [],
      checkedchannel: [],
      //策略表单
      form: {
        strategyName: "",
        strategyType: "",
        templateId: "",
        primaryProductId: "",
        strategyStatus: "1",
        extJson: {},
        maskText: "",
        activityUuid: "",
        activityType: "",
        posterPhoto: "",
        activityLogo: "",
        promotePhoto: "",
        recommendStrategyIds: [],
        unsubscribeStrategyIds: [""],
        linkUrl: "",
      },
      oldform: {},
      //扩展字段
      extJson: {
        jiluBtn: "1",
        jihuoBtn: "1",
        memberBtn: "1",
        chaxunBtn: "1",
        guanzhuBtn: "1",
        tuidingBtn: "1",
        isBuy: "1",
        isMask: "1",
        Zoetrope: "0",
        orderNum: "",
        orderAdd: "",
        orderText: "",
        orderRepeat: "",
        privacy: "0",
        privacyText: "",
        directCharge: null,
        attestation: 0,
        dispose: "",
        activation: "0",
        // 回传api方式
        returnApi: "",
        extendImg: "",
        extendVal: "0",
        treaty: '0',
        treatyText: "",
        fitText: "",
        fitText2: "",
        maskText: "",
        maskText2: "",
        unBuyText: ""
      },
      //策略匹配信息
      rulesform: {
        activeStartDate: "",
        activeStartTime: "00:00:00",
        activeEndDate: "",
        activeEndTime: "23:59:59",
        strategyId: "",
        weeks: "",
        firstChannelId: "",
        secondChannelIds: "",
      },
      btn: "立即创建",

      rules: {
        strategyName: [
          {
            required: true,
            message: "请输入活动名称",
            trigger: "blur",
          },
        ],
        strategyType: [
          {
            required: true,
            message: "请选择策略类型",
            trigger: "change",
          },
        ],
        templateId: [
          {
            required: true,
            message: "请选择模版",
            trigger: "change",
          },
        ],
      },
      // 客户端适配
      disposeList: [
        {
          value: "tencent",
          label: "腾讯客户端",
        },
        {
          value: "aqy",
          label: "爱奇艺客户端",
        },
        {
          value: "bili",
          label: "B站客户端",
        },
        {
          value: "kuaishou",
          label: "快手客户端",
        },
        {
          value: "ksInfo",
          label: "快手信息流",
        },
        {
          value: "ksJhuo",
          label: "快手激活",
        },
        {
          value: "zijie",
          label: "字节跳动信息流",
        },
        {
          value: "zijieStart",
          label: "字节星图信息流",
        },
      ],
    };
  },
  watch: {
    datetimerange (val) {
      if (val) {
        this.rulesform.activeStartDate = val[0];
        this.rulesform.activeEndDate = val[1];
      } else {
        this.rulesform.activeStartDate = "";
        this.rulesform.activeEndDate = "";
      }
    },
    timerange (val) {
      this.rulesform.activeStartTime = val[0];
      this.rulesform.activeEndTime = val[1];
    },
    checkedWeeks (val) {
      this.rulesform.weeks = val
        .map((i) => weekOptions.findIndex((j) => j == i))
        .sort()
        .toString();
    },
  },
  created () {
    document.title = "编辑策略";
  },
  mounted () {
    if (this.$route.query.id) {
      get("/strategyInfoNew/page", {
        id: this.$route.query.id,
      }).then((res) => {
        res = res.data.list[0];
        this.oldform = JSON.parse(JSON.stringify(res));
        this.form = {
          strategyName: res.strategyName,
          strategyType: res.strategyType,
          templateId: res.templateId,
          strategyStatus: res.strategyStatus.toString(),
          primaryProductId: res.primaryProductId,
          maskText: res.maskText,
          activityUuid: res.activityUuid,
          activityType: res.activityType,
          posterPhoto: res.posterPhoto,
          activityLogo: res.activityLogo,
          promotePhoto: res.promotePhoto,
          recommendStrategyIds: res.recommendStrategyIds,
          unsubscribeStrategyIds: res.unsubscribeStrategyIds
            ? res.unsubscribeStrategyIds
            : [],
          viceProductIds: res.viceProductIds,
          linkUrl: res.linkUrl,
          directCharge: res.directCharge,
        };
        if (res.extJson) {
          this.extJson = JSON.parse(res.extJson);
          if (this.extJson.dispose) {
            this.disposeVal = this.extJson.dispose.split(",");
          }
        }

        if (res.activeStartDate) {
          this.datetimerange = [res.activeStartDate, res.activeEndDate];
        }
        if (res.weeks) {
          let checkedWeeks = res.weeks.split(",");
          checkedWeeks.forEach((item) => {
            this.checkedWeeks.push(weekOptions[item]);
          });
        }
        let checkedchannel = [];
        res.channelInfoDatas.forEach((item) => {
          checkedchannel.push([item.firstChannelId, item.secondChannelId]);
        });
        this.checkedchannel = checkedchannel;

        this.rulesform = {
          activeStartTime: res.activeStartTime,
          activeEndTime: res.activeEndTime,
          strategyId: this.$route.query.id,
          firstChannelId: res.firstChannelId,
          secondChannelIds: res.secondChannelIds,
        };
      });
      this.btn = "编辑保存";
    }

    if (this.$route.query.copyId) {
      get("/strategyInfoNew/page", {
        id: this.$route.query.copyId,
      }).then((res) => {
        res = res.data.list[0];
        this.oldform = JSON.parse(JSON.stringify(res));
        this.form = {
          strategyName: res.strategyName + " 副本",
          strategyType: res.strategyType,
          templateId: res.templateId,
          strategyStatus: res.strategyStatus.toString(),
          primaryProductId: res.primaryProductId,
          maskText: res.maskText,
          activityUuid: res.activityUuid,
          activityType: res.activityType,
          posterPhoto: res.posterPhoto,
          activityLogo: res.activityLogo,
          promotePhoto: res.promotePhoto,
          recommendStrategyIds: res.recommendStrategyIds,
          unsubscribeStrategyIds: res.unsubscribeStrategyIds
            ? res.unsubscribeStrategyIds
            : [],
          viceProductIds: res.viceProductIds,
          linkUrl: res.linkUrl,
        };
        if (res.extJson) {
          this.extJson = JSON.parse(res.extJson);
          if (this.extJson.dispose) {
            this.disposeVal = this.extJson.dispose.split(",");
          }
        }
        if (res.activeStartDate) {
          this.datetimerange = [res.activeStartDate, res.activeEndDate];
        }
        if (res.weeks) {
          let checkedWeeks = res.weeks.split(",");
          checkedWeeks.forEach((item) => {
            this.checkedWeeks.push(weekOptions[item]);
          });
        }
        let checkedchannel = [];
        res.channelInfoDatas.forEach((item) => {
          checkedchannel.push([item.firstChannelId, item.secondChannelId]);
        });
        this.checkedchannel = checkedchannel;
        this.rulesform = {
          activeStartTime: res.activeStartTime,
          activeEndTime: res.activeEndTime,
          strategyId: this.$route.query.id,
          firstChannelId: res.firstChannelId,
          secondChannelIds: res.secondChannelIds,
        };
      });
    }

    get("/productInfo/page", {
      pageSize: 9999,
      pageNum: 1,
    }).then((res) => {
      this.productInfoList = res.data.list;
    });
    get("/templateInfo/page", {
      pageSize: 9999,
      pageNum: 1,
    }).then((res) => {
      res.data.list.map((res) => {
        res.templatePhoto =
          process.env.VUE_APP_BASE_IMG_URL + res.templatePhoto;
      });
      this.templateList = res.data.list;
    });
    get("/productInfo/page", {
      pageSize: 9999,
      pageNum: 1,
    }).then((res) => {
      this.productInfoList = res.data.list;
    });
    get("/strategyInfoNew/page", {
      pageSize: 9999,
      pageNum: 1,
    }).then((res) => {
      this.strategyInfoNewList = res.data.list;
    });
    get("/channelInfo/page", {
      pageSize: 9999,
      pageNum: 1,
    }).then((res) => {
      this.options = getArrayClassification({
        data: res.data.list,
        parent: "parentId",
        id: "id",
        child: "children",
      });
      this.props = {
        multiple: true,
        label: "channelName",
        value: "id",
      };
    });
  },
  methods: {
    onSubmit: function (formName) {
      this.$confirm(
        "您确定编辑该策略？当前操作会影响所有上线该策略的渠道",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              let ids = this.form.unsubscribeStrategyIds[0];
              this.form.unsubscribeStrategyIds =
                ids !== "" && ids !== [] && ids ? [ids] : [];
              let template = this.templateList.find((n) => {
                return n.id === this.form.templateId;
              });
              this.extJson.templateCode = template.templateCode;
              if (
                this.extJson.isMask === "1" &&
                (!this.extJson.maskText || this.extJson.maskText === "")
              ) {
                this.$message.error("遮罩文案未填写");
                return false;
              }
              this.form.extJson = JSON.stringify(this.extJson);
              this.rulesform.weeks = this.checkedWeeks
                .map((i) => weekOptions.findIndex((j) => j == i))
                .sort()
                .toString();

              var array1 = JSON.parse(JSON.stringify(this.oldform));
              var array2 = JSON.parse(JSON.stringify(this.form));
              array2["activeEndDate"] = this.rulesform.activeEndDate
                ? this.rulesform.activeEndDate
                : null;
              array2["activeEndTime"] = this.rulesform.activeEndTime
                ? this.rulesform.activeEndTime
                : null;
              array2["activeStartDate"] = this.rulesform.activeStartDate
                ? this.rulesform.activeStartDate
                : null;
              array2["activeStartTime"] = this.rulesform.activeStartTime
                ? this.rulesform.activeStartTime
                : null;
              array2["weeks"] = this.rulesform.weeks;
              let text = "策略：" + this.form.strategyName;
              XEUtils.objectEach(array2, (item, key) => {
                if (item != array1[key]) {
                  if (key == "extJson") {
                    let ext = JSON.parse(item);
                    if (array1[key]) {
                      let arr = JSON.parse(array1[key]);
                      XEUtils.objectEach(ext, (i, k) => {
                        if (i != arr[k]) {
                          text += `\n${k}:${arr[k]} 改为 ${i ? i : "空"}`;
                        }
                      });
                    } else {
                      XEUtils.objectEach(ext, (i, k) => {
                        text += `\n${k}:空 改为 ${i ? i : "空"}`;
                      });
                    }
                  } else {
                    text += `\n${key}:${array1[key]} 改为 ${item ? item : "空"
                      }`;
                  }
                }
              });

              if (this.$route.query.id) {
                post("/strategyInfoNew/savelog", {
                  type: array2.activityType ? array2.activityType : 0,
                  notes: text,
                  strategyId: array2.id,
                  strategyName: array2.strategyName,
                });
                post(
                  "/strategyInfoNew/update/" + this.$route.query.id,
                  this.form
                ).then((res) => {
                  get("/strategyInfoNew/page", {
                    pageSize: 9999,
                    pageNum: 1,
                  }).then((res) => {
                    this.strategyInfoNewList = res.data.list;
                  });
                  let checkedchannel = [];
                  this.checkedchannel.forEach((res) => {
                    checkedchannel.push({
                      firstChannelId: res[0],
                      secondChannelId: res[1],
                    });
                  });
                  this.rulesform.channelInfoDatas = checkedchannel;
                  post(
                    "strategyInfoNew/updateStrategyRules",
                    this.rulesform
                  ).then((res) => {
                    // this.close()
                  });
                  this.$message({
                    message: res.message,
                    type: "success",
                    duration: 3000,
                    offset: 360,
                  });
                  // setTimeout(() => {
                  //   window.close();
                  // }, 1200);
                });
              } else {
                post("/strategyInfoNew/create", this.form).then((res) => {
                  // let params = {
                  //   activeStartDate: '',
                  //   activeStartTime: '00:00:00',
                  //   activeEndDate: '',
                  //   activeEndTime: '23:59:59',
                  //   channelInfoDatas: [{
                  //     firstChannelId: '',
                  //     secondChannelId: ''
                  //   }],
                  //   strategyId: '',
                  //   weeks: ""
                  // }

                  // post('strategyInfoNew/updateStrategyRules', params).then(res => {
                  //   // this.close()
                  // })
                  this.$message({
                    message: res.message,
                    type: "success",
                    duration: 3000,
                    offset: 360,
                  });
                  // setTimeout(() => {
                  //   window.close();
                  // }, 1200);
                });
              }
            } else {
              return false;
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    changePromotionPicposterPhoto (e) {
      this.$set(
        this.form,
        "posterPhoto",
        process.env.VUE_APP_BASE_IMG_URL + e.data
      );
    },
    changePromotionPicactivityLogo (e) {
      this.$set(
        this.form,
        "activityLogo",
        process.env.VUE_APP_BASE_IMG_URL + e.data
      );
    },
    changePromotionPicpromotePhoto (e) {
      this.$set(
        this.form,
        "promotePhoto",
        process.env.VUE_APP_BASE_IMG_URL + e.data
      );
    },
    handleCheckAllChange (val) {
      this.checkedWeeks = val ? weekOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange (value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.weeksList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.weeksList.length;
    },
    close () {
      this.$confirm("此操作不会保存已编辑数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          window.location.href = "about:blank";
          window.close();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    extendImgSuccess (file) {
      // this.extJson.extendImg = process.env.VUE_APP_BASE_IMG_URL + file.data;
      // this.guidancePic.e = file.data;
      this.$set(
        this.extJson,
        "extendImg",
        process.env.VUE_APP_BASE_IMG_URL + file.data
      );
    },
  },
};
</script>

<style lang="scss">
.el-main {
  height: 93vh;
  padding-bottom: 100px;
}

.avatar {
  width: 100%;
  max-width: 500px;
}

.el-divider {
  margin-bottom: 40px !important;

  .el-divider__text {
    font-size: 17px !important;
    font-weight: bold !important;
  }
}
</style>
