<template>
  <div>
    <el-container>
      <el-main>
        <!-- 二级 -->
        <template v-if="form.parentId || $route.query.type == 'erji'">
          <el-form
            ref="form"
            :model="formm"
            :rules="ruless"
            label-width="160px"
          >
            <el-form-item label="渠道名称" prop="channelName">
              <el-input
                placeholder="请输入内容"
                v-model="formm.channelName"
                clearable
                @blur="changeName"
              ></el-input>
              <!-- @change="changeInputer" -->
            </el-form-item>
            <el-form-item label="一级渠道">
              <el-select
                v-model="formm.parentId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteMethod"
                :loading="loading"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.channelName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="二级编码">
              <el-input
                placeholder="自动生成"
                v-model="formm.channelCode"
                disabled
                @change="changeInput"
              ></el-input>
            </el-form-item>
            <el-form-item label="完整编码">
              <el-input
                placeholder="自动生成"
                v-model="formm.fullCode"
                disabled
                @change="changeInput"
              ></el-input>
            </el-form-item>
            <el-form-item label="key">
              <el-input
                placeholder="自动生成"
                v-model="formm.channelKey"
                disabled
                @change="changeInput"
              ></el-input>
            </el-form-item>
            <el-form-item label="渠道类别" prop="channelType">
              <el-select
                v-model="formm.channelType"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上线时间">
              <el-col :span="11">
                <el-date-picker
                  type="datetime"
                  placeholder="选择日期"
                  v-model="formm.onlineTime"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  range-separator="至"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%"
                >
                </el-date-picker>
              </el-col>
            </el-form-item>

            <el-form-item label="绑定策略" prop="strategyId">
              <el-select
                v-model="formm.strategyId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteMethodstrategyId"
                :loading="loading"
              >
                <el-option
                  v-for="item in celueList"
                  :key="item.id"
                  :label="item.strategyName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <span style="margin-left: 20px">
                <el-button
                  @click="refresh"
                  icon="el-icon-refresh"
                  size="mini"
                  content="刷新"
                ></el-button>
              </span>
              <span style="margin-left: 20px">
                <el-button
                  @click="toAdd"
                  icon="el-icon-plus"
                  size="mini"
                  content="新建"
                ></el-button>
              </span>
              <span style="margin-left: 20px">
                <el-button
                  @click="toEdit(form.strategyId)"
                  icon="el-icon-edit"
                  size="mini"
                  content="编辑"
                ></el-button>
              </span>
            </el-form-item>
            <el-form-item label="生效状态">
              <el-radio v-model="formm.channelStatus" :label="0">失效</el-radio>
              <el-radio v-model="formm.channelStatus" :label="1">生效</el-radio>
            </el-form-item>
            <el-form-item label="渠道形态">
              <el-radio v-model="formm.channelPattern" label="0">V1</el-radio>
              <el-radio v-model="formm.channelPattern" label="1">V2</el-radio>
            </el-form-item>
            <el-form-item label="开启WO186域名">
              <el-radio v-model="formm.wotv" label="0">关闭</el-radio>
              <el-radio v-model="formm.wotv" label="1">开启</el-radio>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="ontwo('formm')">{{
                ids ? "立即修改" : "立即创建"
              }}</el-button>
              <el-button @click="close">关闭</el-button>
            </el-form-item>
          </el-form>
        </template>

        <!-- 一级渠道 -->
        <template v-else>
          <el-form ref="form" :model="form" :rules="rules" label-width="160px">
            <el-form-item label="渠道名称" prop="channelName">
              <el-input
                placeholder="请输入内容"
                v-model="form.channelName"
                clearable
                @change="changeInput"
              ></el-input>
            </el-form-item>
            <el-form-item label="一级编码">
              <el-input disabled v-model="form.channelCode"></el-input>
            </el-form-item>
            <el-form-item label="上线时间">
              <el-col :span="11">
                <el-date-picker
                  type="datetime"
                  placeholder="选择日期"
                  v-model="form.onlineTime"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  range-separator="至"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%"
                >
                </el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="合作方">
              <el-input v-model="form.channelPartner"></el-input>
            </el-form-item>
            <el-form-item label="合作方联系人">
              <el-input v-model="form.partnerContacts"></el-input>
            </el-form-item>
            <el-form-item label="合作方联系方式">
              <el-input v-model="form.partnerPhone"></el-input>
            </el-form-item>
            <el-form-item label="负责人姓名">
              <el-input v-model="form.unicomContacts"></el-input>
            </el-form-item>
            <el-form-item label="负责人电话">
              <el-input v-model="form.unicomPhone"></el-input>
            </el-form-item>
            <el-form-item label="生效状态">
              <el-radio v-model="form.channelStatus" :label="0">失效</el-radio>
              <el-radio v-model="form.channelStatus" :label="1">生效</el-radio>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit('form')">{{
                id ? "立即修改" : "立即创建"
              }}</el-button>
              <el-button @click="close">关闭</el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { post, get, put } from "@/api/common";
import XEUtils from "xe-utils";
var text1 = "";
export default {
  name: "SchemeEdit",
  data() {
    return {
      form: {
        channelPattern: "1",
        channelStatus: 1,
        parentId: 0,
      },
      formm: {
        channelPattern: "1",
        channelStatus: 1,
        parentId: this.$route.query.id,
        onlineTime: "",
      },
      oldform: {},

      id: null,
      ids: null,
      options: [],
      loading: false,

      celueList: [],

      typeList: [
        {
          value: "集团渠道",
          label: "集团渠道",
        },
        {
          value: "省分线下渠道",
          label: "省分线下渠道",
        },
        {
          value: "省分线上渠道",
          label: "省分线上渠道",
        },
        {
          value: "互联网渠道",
          label: "互联网渠道",
        },
        {
          value: "自有线上渠道",
          label: "自有线上渠道",
        },
        {
          value: "社会代理和其他渠道",
          label: "社会代理和其他渠道",
        },
      ],

      rules: {
        channelName: [
          {
            required: true,
            message: "请输入渠道名称",
            trigger: "blur",
          },
        ],
      },
      ruless: {
        channelName: [
          {
            required: true,
            message: "请输入渠道名称",
            trigger: "blur",
          },
        ],

        strategyId: [
          {
            required: true,
            message: "请选择渠道名称",
            trigger: "change",
          },
        ],
        channelType: [
          {
            required: true,
            message: "请选择渠道类型",
            trigger: "change",
          },
        ],
      },
      num: null,
    };
  },
  created() {
    // 数据回显
    if (this.$route.query.ids) {
      // console.log(this.$route.query.ids);
      document.title = "修改渠道";
      this.id = this.$route.query.ids;
      get("/channel/info/list", {
        ids: this.id,
      }).then((res) => {
        this.form = res.data[0];
        this.formm = res.data[0];
        this.oldform = JSON.parse(JSON.stringify(res.data[0]));
        // } else {
      });
    }
    document.title = "新增渠道";

    get("/channel/info/page", {
      parentId: 0,
      pageSize: 10,
      pageNum: 1,
    }).then((res) => {
      this.options = res.data.list;
    });
    this.refresh();
  },

  methods: {
    //新增历史记录
    addHistory(type, channelId, text) {
      post("/channel/log/create", {
        type: type,
        notes: text,
        channelId: channelId,
      }).then((res) => {
        console.log(res, "新增历史记录", text);
      });
    },

    ontwo() {
      var array1 = this.oldform;
      var array2 = this.formm;
      // console.log(array1, "array1", array2, "array2");
      XEUtils.objectEach(array2, (item, key) => {
        if (item != array1[key]) {
          text1 += `\n${key}:${array1[key]} 改为 ${item}`;
        }
      });
      // console.log(text1, "text");

      let type = 2;
      let channelId = this.formm.parentId;
      let text = "渠道：" + this.formm.channelName + text1;
      this.addHistory(type, channelId, text); //新增历史记录

      if (this.$route.query.ids) {
        console.log("二级编辑", this.formm);
        delete this.form.createTime;
        this.parentId = 370;
        this.id = this.id;
        put("/channel/info/update", this.formm).then((res) => {
          //   编辑成功
          if (res.data) {
            this.$message({
              message: "编辑成功√",
              type: "success",
              duration: 3000,
              offset: 360,
            });
            setTimeout(() => {
              this.$router.back();
            }, 200);
          }
        });
      } else {
        console.log("二级创建");
        if (
          !this.formm.channelName ||
          !this.formm.channelType
          // !this.formm.strategyId
        ) {
          console.log("无内容");
          this.$message({
            message: "请输入内容",
            type: "error",
            duration: 3000,
            offset: 360,
          });
          return;
        }
        post("/channel/info/create", this.formm).then((res) => {
          this.$message({
            message: "创建成功√",
            type: "success",
          });
          setTimeout(() => {
            this.$router.back();
          }, 200);
        });
      }
    },

    //   点击提交
    onSubmit() {
      // console.log(this.from.parentId);
      this.$confirm("此操作将永久改变数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
       
        let type = 1;
        let channelId = 0;
        let text = "渠道：" + this.form.channelName;
        this.addHistory(type, channelId, text); //新增历史记录

        // 根据id判断编辑或新增
        if (this.id) {
          // 编辑
          delete this.form.createTime;
          this.parentId = 0;
          this.id = this.id;
          //  一级编辑
          if (this.form.parentId == 0) {
            console.log("一级编辑");
            put("/channel/info/update", this.form).then((res) => {
              //   编辑成功
              if (res.data) {
                this.$message({
                  message: "编辑成功√",
                  type: "success",
                  duration: 3000,
                  offset: 360,
                });
                setTimeout(() => {
                  this.$router.back();
                }, 200);
              }
            });
          }
        } else {
          console.log("新增");
          if (!this.form.channelName) {
            console.log("无内容");
            this.$message({
              message: "请输入内容",
              type: "error",
              duration: 3000,
              offset: 360,
            });
            return;
          }
          //新建
          post("/channel/info/create", this.form).then((res) => {
            this.$message({
              message: "创建成功√",
              type: "success",
              duration: 3000,
              offset: 360,
            });
            setTimeout(() => {
              this.$router.back();
            }, 200);
          });
        }
      });
    },
    changeInput() {
      this.form.channelName = this.form.channelName.includes("H5")
        ? this.form.channelName
        : `${this.form.channelName}H5`;
      // this.$set(this.form,'name',`${newV}H5`)
    },

    close() {
      this.$confirm("此操作不会保存已编辑数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$router.back();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    toAdd(e) {
      const routeUrl = this.$router.resolve({
        path: "/schemeV2/schemeAdd",
        query: {
          id: e.id,
        },
      });
      window.open(routeUrl.href, "_blank");

      // this.$router.push("/schemeV2/schemeAdd?")
    },

    // },
    refresh() {
      // get('/strategyInfoNew/page', {
      //   'strategyType': 0,
      //   'pageSize': 9999,
      //   'pageNum': 1,
      //   'strategyType': 0
      // }).then(res => {
      //   this.celueList = res.data.list
      // })
    },
    remoteMethod(query) {
      // let that = this;
      // if (query !== "") {
      //   this.loading = true;
      //   get("/channelInfo/page", {
      //     // parentId: 0,
      //     channelName: query,
      //   }).then((res) => {
      //     this.loading = false;
      //     that.options = res.data.list;
      //   });
      // } else {
      //   this.options = [];
      // }
    },
    remoteMethodstrategyId(query) {
      // let that = this;
      // if (query !== "") {
      //   this.loading = true;
      //   get("/strategyInfoNew/page", {
      //     strategyName: query,
      //     pageSize: 9999,
      //     pageNum: 1,
      //     strategyType: 0,
      //   }).then((res) => {
      //     this.loading = false;
      //     that.celueList = res.data.list;
      //   });
      // } else {
      //   this.options = [];
      // }
    },
    // 渠道名称输入框失焦事件
    changeName() {
      if (!this.num && !this.$route.query.ids)
        if (this.formm.channelName) {
          this.num = 1;
          this.formm.channelName =
            this.$route.query.firstChannelName + this.formm.channelName;
        }
    },
  },
};
</script>

<style scoped></style>
