<template>
  <div class="directional-edit">
    <EditComp v-model="baseForm" :config="baseData" ref="base"></EditComp>
    <EditComp v-model="baseForm" :config="freeFlowData" ref="base1"></EditComp>
    <EditComp v-model="baseForm" :config="PRMData" ref="base2">
      <el-form-item label="PRM产品分账比例" prop="ratioSheng" :rules="rules1">
        <el-input v-model="baseForm.ratioSheng" type="number" placeholder="省分（%）"></el-input>
      </el-form-item>
      <el-form-item prop="ratioOnline" label-width="10px" :rules="rules2">
        <el-input v-model="baseForm.ratioOnline" type="number" placeholder="在线（%）"></el-input>
      </el-form-item>
    </EditComp>
    <EditComp v-model="baseForm" :config="CBData" ref="base3">
      <template>
        <div class="cb-list" v-for="(val, i) in cbList">
          <i class="el-icon-circle-plus-outline" @click="updateCbList('add')"></i>
          <el-form-item label="ELEMTID" class="item-1">
            <el-input v-model="cbList[i].elemtId" placeholder="请输入ELEMTID"></el-input>
          </el-form-item>
          <el-form-item label="ELMENTTYPE" class="item-2">
            <el-input v-model="cbList[i].elemtType" placeholder="请输入ELMENTTYPE"></el-input>
          </el-form-item>
          <i class="el-icon-remove-outline" @click="updateCbList('delete', i)"></i>
        </div>
      </template>
    </EditComp>
    <EditComp v-model="baseForm" :config="QYData" ref="base4"> </EditComp>
    <EditComp v-model="baseForm" :config="CPData" ref="base6"></EditComp>

    <EditComp v-model="baseForm" :config="DGData" ref="base5">
      <template>
        <div class="dg-list">
          <template v-if="baseForm.type == '1'">
            <el-form-item label="月资费" prop="price" label-width="80px" :rules="rules3">
              <el-input v-model="baseForm.price" placeholder="请输入月资费"></el-input>
            </el-form-item>
            <el-form-item label="是否自动续订" label-width="120px">
              <el-switch active-text="是" inactive-text="否" v-model="baseForm.orderAutoRenew" active-value="1"
                inactive-value="2"></el-switch>
            </el-form-item>
            <el-form-item label="是否当月生效" label-width="120px">
              <el-switch active-text="是" inactive-text="否" active-value="1" inactive-value="2"
                v-model="baseForm.orderValidMonth"></el-switch>
            </el-form-item>
          </template>
          <!-- 首月资费 -->
          <template v-if="baseForm.type == '2'">
            <el-form-item label="首月资费" prop="orderFirstmonthFee" label-width="80px" :rules="rules3">
              <el-input v-model="baseForm.orderFirstmonthFee" placeholder="请输入首月资费"></el-input>
            </el-form-item>
            <el-form-item label="次月资费" prop="orderNextmonthFee" label-width="80px" :rules="rules3">
              <el-input v-model="baseForm.orderNextmonthFee" placeholder="请输入次月资费"></el-input>
            </el-form-item>
            <el-form-item label="合约期" prop="orderPeriod" label-width="80px" :rules="rules4">
              <el-input-number v-model="baseForm.orderPeriod" placeholder="请设置合约期">
              </el-input-number>
            </el-form-item>
          </template>
        </div>
      </template>
    </EditComp>
    <EditComp v-model="baseForm" :config="timeData" ref="base7"> </EditComp>
    <EditComp v-model="baseForm" :config="fileData" ref="base8">
      <el-form-item label="文件上传">
        <div v-if="typeShow == 'edit' || typeShow == 'add'">
          <el-upload :auto-upload="false" :file-list="fileList" multiple :on-change="onChange" :on-remove="handleRemove"
            action="#" class="upload-demo" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              支持文件上传：pdf、.xlsx、docx、jpg、png、gif
            </div>
            <div slot="tip" class="el-upload__tip" style="font-size: 14px; color: red">
              可上传产品集团相关发文等；在线公司报审备案文件；
            </div>
          </el-upload>
        </div>
        <div class="update-list" v-else>
          <template v-if="fileNameList.length > 0">
            <div class="update-item" v-for="(item, i) in fileNameList" :key="i" @click="download(item.url, i)">
              <i class="el-icon-folder"></i>
              <span>{{ item.name }}</span>
            </div>
          </template>
          <div class="" v-else>暂未传文件</div>
        </div>
      </el-form-item>
    </EditComp>
    <EditComp v-model="baseForm" :config="huChi" ref="base9" v-if="typeShow == 'view'">
      <el-form-item label="产品互斥规则">
        <el-input v-model="baseForm.orderHuchiToName" placeholder="请选择产品互斥规则"></el-input>
      </el-form-item>
      <el-form-item label="产品关联退订">
        <el-input v-model="baseForm.relaUnsubToName" placeholder="请选择产品关联退订"></el-input>
      </el-form-item>
    </EditComp>
    <div class="submit-data">
      <el-button @click="$router.back()">取消</el-button>
      <el-button type="primary" @click="saveData" v-if="typeShow == 'edit' || typeShow == 'add'">确认</el-button>
    </div>
    <el-dialog title="请选择产品审核模板" :visible.sync="dialogVisible" width="30%" center>
      <el-form>
        <el-form-item label="审核模板">
          <el-select v-model="examine" placeholder="">
            <el-option v-for="(val, i) in examineList" :key="i" :label="val" :value="val"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import EditComp from "@/views/directional/components/editComp.vue";
import {
  baseData,
  freeFlowData,
  PRMData,
  CBData,
  QYData,
  DGData,
  CPData,
  timeData,
  fileData,
  filetersName,
  initFormData,
  initFreeFlowData,
  huChi,
} from "./editConfig";
import { productDetail, productAdd, productUpdate } from "@/api/directional";
import { post, get } from "@/api/common";

import { Message } from "element-ui";
import { mapState } from "vuex";
export default {
  data () {
    return {
      //审核模板弹窗
      dialogVisible: false,
      //   审核模板
      examine: "",
      //   审核模板列表
      examineList: [],
      //基本信息配置
      baseData,
      //   免流
      freeFlowData,
      // prm
      PRMData,
      //   c d
      CBData,
      //   权益
      QYData,
      //   订购
      DGData,
      //   产品短信模板
      CPData,
      //   时间
      timeData,
      //   文件
      fileData,
      huChi,
      baseForm: initFormData,
      // 初始化数据
      initFormData: {},
      rules1: [{ required: true, message: "请输入省分比例" }],
      rules2: [{ required: true, message: "请输入在线比例" }],
      rules3: [{ required: true, message: "请输入资费信息" }],
      rules4: [{ required: true, message: "请选择合约期" }],
      //   上传文件
      //文件列表
      fileList: [],
      fileNameList: [],
      imgUrl: process.env.VUE_APP_BASE_IMG_URL,
      imgapi: process.env.VUE_APP_BASE_IMG_API,
      arr: [],
      //   上传地址
      uploadUrl: "",

      //表单验证
      nameList: ["base", "freeFlow", "prm", "cb", "qy", "dg", "cp", "time"],
      //  显示类型
      typeShow: "view",
      // 多选数据
      // 回传数据 key 二维数据
      keyArr: [],
      // 列表 cb
      cbList: [{ elemtId: "", elemtType: "" }],
      // 文件列表
      fileUploadOperList: [],
      //  添加表单key
      addFormKey: [],
    };
  },
  computed: {
    ...mapState({
      userName: (state) => state.user.name,
    }),
  },
  components: { EditComp },
  methods: {
    // 下载文件
    download (url, i) {
      var link = document.createElement("a");

      link.href = this.imgUrl + url;
      link.setAttribute("download", this.fileNameList[i].name);

      link.style.display = "none";

      link.click();
      // window.open(this.imgUrl + url);
    },
    // 文件选择
    onChange (file, fileList) {
      this.fileList = fileList;
      let formData = new FormData();
      formData.append("file", file.raw);
      formData.append("type", 1);
      if (file.raw) {
        post(this.imgapi, formData).then((res) => {
          let obj = {
            uid: file.uid,
            url: this.imgUrl + res.data,
          };
          this.fileNameList.push({
            name: file.name,
            uid: file.uid,
            url: res.data,
          });
          this.arr.push(obj);
        });
      }
    },
    // 删除文件
    handleRemove (file, fileList) {
      this.fileNameList.forEach((item, i) => {
        if (item.uid == file.uid) {
          this.fileNameList.splice(i, 1);
        }
      });
      this.fileList = fileList;
    },
    setDisabled () {
      let arr = [
        "baseData",
        "freeFlowData",
        "PRMData",
        "CBData",
        "QYData",
        "DGData",
        "CPData",
        "timeData",
        "fileData",
      ];
      arr.map((data) => {
        if (this[data]?.list instanceof Array) {
          this[data].list.forEach((el) => {
            if (filetersName.indexOf(el.key) !== -1) {
              el.disabled = false;
            } else {
              el.disabled = true;
            }
          });
        }
      });
    },
    initFileList (data) {
      let dataSet = [];
      if (data) {
        dataSet = JSON.parse(data);
      }
      this.fileNameList = dataSet;
      this.fileList = dataSet;
    },
    // 比对数据是否修改
    compareData () {
      let flag = false;
      let objName = Object.keys(this.baseForm);
      objName.map((val, i) => {
        if (this.baseForm[val] == this.initFormData[val]) flag = true;
      });
      return flag;
    },
    // cb列表
    updateCbList (type, i) {
      if (type == "add") {
        this.cbList.push({ elemtId: "", elemtType: "" });
      }
      if (this.cbList.length == 1) {
        Message.warning("至少保留一条数据");
        return;
      }
      if (type == "delete" && this.cbList.length > 1) {
        this.cbList.splice(i, 1);
      }
    },
    //  上传文件成功回调
    handleAvatarSuccess (res, file) {
      // console.log(res, file);
    },
    // 保存草稿
    saveDraft () { },
    // 提交审核
    saveData (flag) {
      let arr = [];
      let arrKey = Object.keys(this.$refs);
      arrKey.map((val) => {
        arr.push(
          new Promise((resolve, reject) => {
            this.$refs[val].$refs.formName.validate((valid) => {
              if (valid) resolve();
            });
          })
        );
      });
      Promise.all(arr).then(() => {
        if (this.typeShow == "add") {
          //全部验证通过
          let data = this.flagValue();
          data.freeFlowType = data.add.freeFlowType;
          productAdd(data).then((res) => {
            if (res.code == 10000) {
              Message.success("保存成功");
              this.$router.push("/directional/directionalList");
            }
          });
        } else {
          productUpdate(this.flagValue(), this.$route.query.id).then((res) => {
            if (res.code == 10000) {
              Message.success("修改成功");
              this.getDetail();
              this.$router.push("/directional/directionalList");
            }
          });
        }
        //写保存方法
      });
    },
    // 保存数据结构
    saveDataStructure (data) {
      let keyArr = [];
      Object.keys(data).map((val, i) => {
        keyArr.push({ val, list: [] });
        if (data[val] instanceof Object) {
          keyArr[i].list = Object.keys(data[val]);
        }
      });
      return keyArr;
    },
    // 获取详情
    async getDetail () {
      this.addFormKey = this.saveDataStructure(initFreeFlowData);
      // console.log(this.addFormKey);
      if (this.typeShow == "add") return;
      let { code, data } = await productDetail(this.$route.query.id);
      if (code === 10000) {
        Object.keys(data).map((val, i) => {
          this.keyArr.push({ val, list: [] });
          if (data[val] instanceof Object) {
            this.keyArr[i].list = Object.keys(data[val]);
          }
        });

        // Message.success("获取详情成功");
        if (this.typeShow == "add") return;
        this.baseForm = {
          ...data.add,
          ...data.aopConfig,
          ...data.info,
          ...data.smsSendContent,
          content: data.content,
          freeFlowType2: data.freeFlowType,
          productIdCB: data.aopConfig.productId,
          productIdJy: data.info.productId,
          orderHuchiToName: data.orderHuchiToName,
          relaUnsubToName: data.relaUnsubToName,
        };
        // console.log(this.baseForm, "baseForm");
        if (this.typeShow !== "add" && data.add.selfSave == 1) {
          this.setDisabled();
        }
        this.initFileList(data.add.fileUploadOper);
        // console.log(this.baseForm, "baseForm");
        if (this.baseForm.elemtId !== null) {
          this.cbList = JSON.parse(this.baseForm.elemtId);
        }
        this.initFormData = JSON.parse(JSON.stringify(this.baseForm));
      }
    },
    flagValue () {
      let obj = {};
      let keyArrs = this.typeShow == "add" ? this.addFormKey : this.keyArr;
      keyArrs.map((item, i) => {
        // 如果是对象
        if (item.list.length != 0) {
          obj[item.val] = {};
          item.list.map((val1, i1) => {
            let type = this.baseForm[val1];
            if (type !== undefined || type !== null || type !== "") {
              obj[item.val][val1] = type;
            }
          });
        }
      });
      // console.log(obj, "obj");
      obj.info.productId = this.baseForm.productIdJy;
      obj.aopConfig.productId = this.baseForm.productIdCB;
      obj.add.elemtId = JSON.stringify(this.cbList);
      // obj.info.creater = this.userName;
      obj.add.fileUploadOper = JSON.stringify(this.fileNameList);
      return obj;
    },
  },
  created () {
    let path = this.$route.path;
    if (path.indexOf("Edit") >= 0) {
      this.typeShow = "edit";
    } else if (path.indexOf("View") >= 0) {
      this.typeShow = "view";
    } else if (path.indexOf("Add") >= 0) {
      this.typeShow = "add";
    }

    this.getDetail();
  },
  watch: {
    "baseForm.startdate" () {
      // 开始时间结束时间不为空
      if (this.baseForm.startdate && this.baseForm.enddate) {
        let start = new Date(this.baseForm.startdate).getTime();
        let end = new Date(this.baseForm.enddate).getTime();
        if (start > end) {
          Message.warning("开始时间不能大于结束时间");
          this.baseForm.enddate = "";
        }
      }
    },
    "baseForm.enddate" () {
      // 开始时间结束时间不为空
      if (this.baseForm.startdate && this.baseForm.enddate) {
        let start = new Date(this.baseForm.startdate).getTime();
        let end = new Date(this.baseForm.enddate).getTime();
        if (start > end) {
          Message.warning("开始时间不能大于结束时间");
          this.baseForm.enddate = "";
        }
      }
    },
  },
};
</script>
<style scoped lang="scss">
.directional-edit {
  padding: 20px;
  height: calc(100vh - 50px);
  overflow-y: scroll;

  .align-base {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .cb-list {
    display: flex;
    align-items: center;
    width: 100%;
    position: relative;
    margin-bottom: 20px;

    .item-1,
    .item-2 {
      width: 40%;
      max-width: 40%;
      margin-right: 10%;
      margin-bottom: 0;
    }

    i {
      position: absolute;
      font-size: 20px;
    }

    .el-icon-circle-plus-outline {
      left: 2%;
      cursor: pointer;
    }

    .el-icon-remove-outline {
      right: 6%;
      cursor: pointer;
    }
  }

  .dg-list {
    width: 60%;
    display: flex;
  }

  .submit-data {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;

    .el-button:nth-child(1) {
      margin-left: 20px;
    }

    .el-button+.el-button {
      margin-left: 50px;
    }
  }

  .update-list {
    width: 100%;
    display: flex;
    flex-wrap: wrap;

    .update-item {
      min-width: 120px;
      width: 120px;
      height: 100px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      margin-bottom: 10px;
      margin-right: 10px;
      box-shadow: 0 0 5px #ccc;

      i {
        font-size: 40px;
      }

      span {
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 80%;
      }
    }
  }
}
</style>
