<template>
  <div>
    <el-container>
      <el-main>
        <el-form
          :model="form"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
        >
          <el-form-item label="策略名称" prop="name">
            <el-input style="width: 300px" v-model="form.name" />
          </el-form-item>
          <el-form-item label="策略备注" prop="describeContent">
            <el-input
              type="textarea"
              :autosize="{ minRows: 1, maxRows: 4 }"
              style="width: 60%"
              v-model="form.describeContent"
            />
          </el-form-item>
          <el-form-item label="使用模板">
            <el-select
              v-model="form.templateName"
              style="width: 300px"
              clearable
              placeholder="请选择模板"
            >
              <el-option
                v-for="item in templateList"
                :key="item.templateCode"
                :label="item.templateName"
                :value="item.templateCode"
              >
                <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>
          </el-form-item>
          <el-form-item label="启用遮罩">
            <el-switch
              style="width: 300px"
              v-model="form.enableMask"
              active-text="启用"
              inactive-text="不启用"
              :active-value="1"
              :inactive-value="null"
            />
          </el-form-item>
          <el-form-item label="遮罩文本">
            <el-input
              type="textarea"
              :autosize="{ minRows: 1, maxRows: 4 }"
              style="width: 60%"
              v-model="form.maskText"
            />
          </el-form-item>
          <el-form-item label="订购拦截">
            <el-switch
              style="width: 300px"
              v-model="form.interceptRule"
              active-text="启用"
              inactive-text="不启用"
              active-value="1"
              :inactive-value="null"
            />
          </el-form-item>
          <el-form-item label="推荐策略">
            <el-select
              v-model="recommendStrategy"
              multiple
              filterable
              placeholder="请选择"
              @change="recommendChange"
            >
              <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.cancelRule"
              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-switch
              style="width: 300px"
              v-model="form.status"
              active-text="生效中"
              inactive-text="未生效"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>

          <el-divider content-position="left">策略匹配</el-divider>

          <el-form-item label="渠道选择">
            <el-cascader
              v-model="checkedchannel"
              :options="options"
              :props="props"
              show-all-levels
              clearable
              @change="handleChange"
              filterable
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="产品选择">
            <el-select
              v-model="spids"
              multiple
              filterable
              placeholder="请选择"
              @change="spidChange"
            >
              <el-option
                v-for="(item, index) in productInfoList"
                :key="index"
                :label="item.productName+'/'+item.remark+'/'+item.spid"
                :value="item.spid"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="地区选择">
            <el-select
              v-model="locations"
              multiple
              filterable
              placeholder="请选择"
              @change="locationChange"
            >
              <el-option
                v-for="item in locationlist"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </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="form.beginTime"
              :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="form.endTime"
              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: [],
      //地区列表
      locationlist: [
        "北京",
        "上海",
        "天津",
        "重庆",
        "黑龙江",
        "吉林",
        "辽宁",
        "内蒙古",
        "河北",
        "新疆",
        "甘肃",
        "青海",
        "陕西",
        "宁夏",
        "河南",
        "山东",
        "山西",
        "安徽",
        "湖北",
        "湖南",
        "江苏",
        "四川",
        "贵州",
        "云南",
        "广西",
        "西藏",
        "浙江",
        "江西",
        "广东",
        "福建",
        "台湾",
        "海南",
        "香港",
        "澳门",
      ],

      //策略匹配
      activeNames: ["1"],
      datetimerange: [],
      timerange: [],
      recommendStrategy: [],
      checkAll: true,
      weeksList: weekOptions,
      isIndeterminate: true,
      checkedWeeks: [],
      //渠道选择
      props: {
        multiple: true,
      },
      options: [],
      checkedchannel: [],
      spids: [],
      locations: [], //策略表单
      form: {
        beginDateTime: "",
        beginTime: "00:00:00",
        cancelRule: "",
        describeContent: "",
        enableMask: 0,
        endDateTime: "",
        endTime: "23:59:59",
        firstChannel: "",
        id: 0,
        interceptRule: "",
        maskText: "",
        name: "",
        recommendStrategy: "",
        secondChannel: "",
        status: null,
        templateName: "",
        week: "0,1,2,3,4,5,6",
      },
      btn: "立即创建",

      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
      },
    };
  },
  watch: {
    datetimerange(val) {
      if (val) {
        this.form.beginDateTime = val[0];
        this.form.endDateTime = val[1];
      } else {
        this.form.beginDateTime = "";
        this.form.endDateTime = "";
      }
    },
    timerange(val) {
      this.form.beginTime = val[0];
      this.form.endTime = val[1];
    },
    checkedWeeks(val) {
      this.form.week = val
        .map((i) => weekOptions.findIndex((j) => j == i))
        .sort()
        .toString();
      // console.log(this.form.week)
    },
  },
  created() {
    document.title = "编辑策略";
  },
  mounted() {
    if (this.$route.query.id) {
      get("/strategyproinfo/page", { id: this.$route.query.id }).then((res) => {
        res = res.data.list[0];
        this.form = {
          spids: res.spids,
          beginDateTime: res.beginDateTime,
          beginTime: res.beginTime,
          cancelRule: res.cancelRule,
          describeContent: res.describeContent,
          enableMask: res.enableMask,
          endDateTime: res.endDateTime,
          endTime: res.endTime,
          firstChannel: res.firstChannel,
          interceptRule: res.interceptRule,
          maskText: res.maskText,
          name: res.name,
          recommendStrategy: res.recommendStrategy,
          secondChannel: res.secondChannel,
          status: res.status,
          templateName: res.templateName,
          week: res.week,
          location: res.location,
        };
        if (res.cancelRule) {
          this.form.cancelRule = res.cancelRule * 1;
        }
        if (res.recommendStrategy) {
          let list = res.recommendStrategy.split(",");
          list.forEach((item) => {
            this.recommendStrategy.push(item * 1);
          });
        }
        if (res.spids) {
          this.spids = res.spids.split(",");
        }
        if (res.location) {
          this.locations = res.location.split(",");
        }
        if (res.beginDateTime) {
          this.datetimerange = [res.beginDateTime, res.endDateTime];
        }
        let checkedWeeks = res.week.split(",");
        checkedWeeks.forEach((item) => {
          this.checkedWeeks.push(weekOptions[item]);
        });
        let checkedchannel = [];
        let firstChannel = res.firstChannel.split(",");
        let secondChannel = res.secondChannel.split(",");
        secondChannel.forEach((item, key) => {
          checkedchannel.push([firstChannel[key], item]);
        });
        this.checkedchannel = checkedchannel;
      });
      this.btn = "编辑保存";
    }

    if (this.$route.query.copyId) {
      get("/strategyproinfo/page", { id: this.$route.query.copyId }).then(
        (res) => {
          console.log(res);
          res = res.data.list[0];
          this.form = {
            spids: res.spids,
            beginDateTime: res.beginDateTime,
            beginTime: res.beginTime,
            cancelRule: res.cancelRule,
            describeContent: res.describeContent,
            enableMask: res.enableMask,
            endDateTime: res.endDateTime,
            endTime: res.endTime,
            firstChannel: res.firstChannel,
            interceptRule: res.interceptRule,
            maskText: res.maskText,
            name: res.name + " 副本",
            recommendStrategy: res.recommendStrategy,
            secondChannel: res.secondChannel,
            status: res.status,
            templateName: res.templateName,
            week: res.week,
            location: res.location,
          };
          console.log(this.form);
          if (res.cancelRule) {
            this.form.cancelRule = res.cancelRule * 1;
          }
          if (res.recommendStrategy) {
            let list = res.recommendStrategy.split(",");
            list.forEach((item) => {
              this.recommendStrategy.push(item * 1);
            });
          }
          if (res.spids) {
            this.spids = res.spids.split(",");
          }
          if (res.location) {
            this.locations = res.location.split(",");
          }
          if (res.activeStartDate) {
            this.datetimerange = [res.beginDateTime, res.endDateTime];
          }
          let checkedWeeks = res.week.split(",");
          checkedWeeks.forEach((item) => {
            this.checkedWeeks.push(weekOptions[item]);
          });
          let checkedchannel = [];
          let firstChannel = res.firstChannel.split(",");
          let secondChannel = res.secondChannel.split(",");
          secondChannel.forEach((item, key) => {
            checkedchannel.push([firstChannel[key], item]);
          });
          this.checkedchannel = checkedchannel;
        }
      );
    }

    get("/productInfo/list", { 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("/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: "channelKey",
      };
    });
  },
  methods: {
    // 提交表单
    onSubmit: function (formName) {
      this.$confirm(
        "您确定编辑该策略？当前操作会影响所有上线该策略的渠道",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.form.week = this.checkedWeeks
                .map((i) => weekOptions.findIndex((j) => j == i))
                .sort()
                .toString();
              console.log(this.form);
              if (this.$route.query.id) {
                post(
                  "/strategyproinfo/update/" + this.$route.query.id,
                  this.form
                ).then((res) => {
                  this.$message({
                    message: res.message,
                    type: "success",
                    duration: 3000,
                    offset: 360,
                  });
                  setTimeout(() => {
                      window.close()
                  }, 1200)
                });
              } else {
                post("/strategyproinfo/create", this.form).then((res) => {
                  this.$message({
                    message: res.message,
                    type: "success",
                    duration: 3000,
                    offset: 360,
                  });
                  setTimeout(() => {
                      window.close()
                  }, 1200)
                });
              }
            } else {
              console.log("error submit!!");
              return false;
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 星期全选
    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;
    },
    // 渠道选择
    handleChange(value) {
      console.log(value);
      let firstChannel = "";
      let secondChannel = "";
      value.forEach((val) => {
        firstChannel = firstChannel + val[0] + ",";
        secondChannel = secondChannel + val[1] + ",";
      });
      this.form.firstChannel = firstChannel.substring(
        0,
        firstChannel.length - 1
      );
      this.form.secondChannel = secondChannel.substring(
        0,
        secondChannel.length - 1
      );
      this.checkedchannel = value;
    },
    // 推荐策略切换
    recommendChange(value) {
      let ids = "";
      value.forEach((item) => {
        ids = ids + item + ",";
      });
      this.form.recommendStrategy = ids.substring(0, ids.length - 1);
    },
    // 产品切换
    spidChange(value) {
      let ids = "";
      value.forEach((item) => {
        ids = ids + item + ",";
      });
      this.form.spids = ids.substring(0, ids.length - 1);
      console.log(this.form.spids);
    },
    // 地区切换
    locationChange(value) {
      let ids = "";
      value.forEach((item) => {
        ids = ids + item + ",";
      });
      this.form.location = ids.substring(0, ids.length - 1);
      console.log(this.form.location);
    },
    // 关闭页面
    close() {
      this.$confirm("此操作不会保存已编辑数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          window.location.href = "about:blank";
          window.close();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
  },
};
</script>

<style lang="scss">
.el-main {
  height: 93vh;
  padding-bottom: 100px;
  .el-form {
    margin-bottom: 50px;
  }
  .el-divider--horizontal {
    margin: 70px 0 30px 0;
  }
}

.avatar {
  width: 100%;
  max-width: 500px;
}
</style>
