<template>
  <div class="upload_infor">
    <form>
      <div class="dataName">
        <span>资料名称</span
        ><input
          type="text"
          class="inputStyle focusStyle"
          v-model="inforName"
          @focus="hideTip"
          @blur="checkName()"
        />
        <p v-show="tipFlag">{{ tipText }}</p>
      </div>
      <div class="inforDes">
        <span>资料描述</span
        ><textarea
          name="inforDes"
          cols="40"
          rows="4"
          class="focusStyle"
          v-model="inforDes"
        ></textarea>
      </div>
      <div class="selectType">
        <p>选择类型</p>
        <div>
          <span>素材时间</span>
          <input
            type="month"
            :min="localMonth"
            class="inputStyle"
            v-model="materialTime"
            @change="materialTimeChange"
          />
          <span style="margin-left: 30px">经销商范围</span>
          <select class="selectStyle" v-model="scope" autocomplete="off">
            <option value="1">共通</option>
            <option value="0">部分</option>
          </select>
        </div>
      </div>
      <div v-show="scope === '0'">
        <p>权限设置</p>
        <div class="addByArea">
          <span>按区域添加</span>
          <div v-for="(item, index) in areaList" :key="index">
            <input
              type="checkbox"
              :value="item"
              v-model="checkedBoxList"
              @click="clickCheckbox(index)"
            /><span>{{ item }}</span>
          </div>
          <button @click.prevent="addByArea">添加</button>
        </div>
        <div class="addByCustomize">
          <span>自定义添加</span>
          <input
            id="dlr"
            list="dlrs"
            class="inputStyle"
            v-model="addByCustomize"
          />
          <datalist id="dlrs">
            <option v-for="(item, index) in dlrList" :key="index" :value="item">
              {{ item }}
            </option>
          </datalist>
          <button @click.prevent="addBySelf">添加</button>
        </div>
        <div class="addByGroup">
          <span>按小组添加</span>
          <div class="selectBox">
            <div class="group_select" @click="showOption">
              <p>请选择</p>
              <img src="../../img/select_arrow.png" />
            </div>
            <div class="optionBox" v-if="optionFlag">
              <ul>
                <li v-for="(item, index) in groupList" :key="index">
                  <p>{{ item.groupName }}</p>
                  <img
                    src="../../img/add.png"
                    @click="addGroup(index)"
                    v-if="item.flag"
                  />
                  <img
                    src="../../img/delete.png"
                    @click="deleteGroup(index)"
                    v-else
                  />
                </li>
              </ul>
            </div>
          </div>
          <button @click.prevent="addByGroup">添加</button>
        </div>
      </div>
    </form>
    <div v-show="scope === '0'">
      <div class="count">
        <Count :sum="sum" />
      </div>
      <div class="table">
        <UpLoadTable
          :tableData="tableData"
          @change_icon="changeIcon"
          :pageSize="pageSize"
          :currentPage="currentPage"
        />
      </div>
      <div class="page" v-show="sum > 0">
        <Tablepage
          :totalPage="totalPage"
          :currentPage="currentPage"
          @change_page="changePage"
          @jump_page="jumpPage"
        />
      </div>
    </div>

    <div class="uploadFile">
      <p>附件</p>
      <label for="fileInput" @change="getFileInfo($event)"
        >导入<input type="file" name="fileName" id="fileInput" multiple
      /></label>
      <div class="fileDes">
        <p v-for="(item, index) in fileDes" :key="index">{{ item }}</p>
      </div>
    </div>
    <button @click="submit" class="submitBtn">提交</button>
    <TipModal
      :tipFlag="tipModalFlag"
      :tipText="tipModalText"
      @close_tip_modal="closeTipModal"
    />
  </div>
</template>

<script>
import UpLoadTable from "./components/UploadInforTable";
import Count from "../../components/Count";
import Tablepage from "../../components/TablePage";
import TipModal from "../../components/TipModal";
export default {
  props: {
    isManufacturer: {
      type: String,
      default: "distributor",
    },
  },
  components: {
    UpLoadTable,
    Count,
    Tablepage,
    TipModal,
  },
  watch: {},
  data() {
    return {
      allDataNameList: [],
      tipFlag: false, // 是否展示提示
      tipText: "资料名称不能重复，请重新输入",
      inforName: "",
      inforDes: "",
      materialTime: "",
      scope: "1", //1为共通 ， 0为部分
      checkedBoxList: [], // 多选框选中的值
      addByCustomize: "",
      dlrList: [], // 自定义添加
      addGroupList: [], // 添加的小组
      optionFlag: false, // 是否展示按小组添加的选择栏
      fileDes: [], // 上传的文件名
      file: "", //上传的文件
      // 表格配置
      sum: 0, // 一共有多少条数据
      pageSize: 20, // 每页展示的数据
      currentPage: 1,
      areaList: [], // 按区域添加
      groupList: [], // 按小组添加
      localMonth: "",
      tableData: [], // 表格显示的数据
      allDlr: [], // 所有进销商数据
      idList: [],
      tipModalFlag: false,
      tipModalText: "",
    };
  },
  computed: {
    // 表格总页数
    totalPage() {
      return Math.ceil(this.sum / this.pageSize);
    },
  },
  methods: {
    // 检查名字是否重复 失去焦点判断
    checkName: function () {
      let include = this.allDataNameList.indexOf(this.inforName);
      if (!this.inforName) {
        this.tipText = "资料名不能为空";
        this.tipFlag = true;
        return;
      } else if (include > 0) {
        this.tipText = "资料名称不能重复，请重新输入";
        this.tipFlag = true;
        return;
      }
    },
    // 名字不重复，隐藏提示
    hideTip: function () {
      this.tipText = "资料名称不能重复，请重新输入";
      this.tipFlag = false;
    },
    // 素材时间变化
    materialTimeChange: function () {
      // this.materialTime = this.localMonth.replace('-', '/');
      console.log(this.materialTime);
    },
    // 显示隐藏按小组添加下拉框
    showOption() {
      this.optionFlag = !this.optionFlag;
    },
    // 保证多选框东区和其他的多选框互斥
    clickCheckbox(i) {
      let list = this.checkedBoxList;
      let include = list.indexOf("东区");
      console.log(i, include);
      // if (i === 0) {
      //   this.checkedBoxList = [];
      //   return;
      // }
      // if (include >= 0) {
      //   this.checkedBoxList.splice(0, 1);
      // }
    },
    // 点击按区域添加button
    addByArea: function () {
      if (this.checkedBoxList.length !== 0) {
        let strReq = this.checkedBoxList.join(",");
        let req = {
          localArea: strReq,
        };
        this.getAllDlr(req);
      }
    },
    // 自定义添加
    addBySelf: function () {
      if (this.addByCustomize) {
        let dataObj = {
          queryParams: this.addByCustomize,
        };
        this.getAllDlr(dataObj, false, true);
      }
    },
    // 按小组添加，增加小组
    addGroup: function (index) {
      this.groupList[index].flag = !this.groupList[index].flag;
    },
    // 按小组添加，删除小组
    deleteGroup: function (index) {
      this.groupList[index].flag = !this.groupList[index].flag;
    },
    // 点击按小组添加  添加按钮
    addByGroup: function () {
      this.addGroupList = [];
      this.groupList.forEach((element) => {
        if (!element.flag) {
          this.addGroupList.push(element.id);
        }
      });
      if (this.addGroupList.length !== 0) {
        let strReq = this.addGroupList.join(",");
        let req = {
          groupId: strReq,
        };
        this.getAllDlr(req);
        this.optionFlag = false;
      } else {
        alert("没有选择一个或多个小组");
      }
    },
    // 筛选
    changeIcon: function (i) {
      let index = (this.currentPage - 1) * this.pageSize + i;
      this.allDlr[index].flag = !this.allDlr[index].flag;
    },
    // 选中经销商的id 组成列表
    dlrIdList: function () {
      this.idList = [];
      this.allDlr.forEach((element) => {
        if (element.flag) {
          this.idList.push(element.id);
        }
      });
    },
    // 关闭提示框
    closeTipModal: function () {
      this.tipModalFlag = false;
      this.$router.go(0);
    },
    // 获取某一页面的数据，展示在表格
    changePage: function (page) {
      this.currentPage = page;
      this.tableData = this.allDlr.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
    // 点击上一页，下一页，首页，尾页
    jumpPage: function (item) {
      switch (item) {
        case 1:
          this.currentPage = 1;
          break;
        case 2:
          this.currentPage = this.currentPage - 1;
          break;
        case 3:
          this.currentPage = this.currentPage + 1;
          break;
        case 4:
          this.currentPage = this.totalPage;
          break;
      }
      this.tableData = this.allDlr.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
    // 点击提交，检查名字是否重复，获取数据
    submit: function () {
      this.checkName();
      if (!this.tipFlag) {
        if (!this.inforDes) {
          alert("资料描述不能为空");
          return;
        }
        if (!this.materialTime) {
          alert("素材时间不能为空");
          return;
        }
        if (!this.file) {
          alert("请导入附件");
          return;
        }
        this.dlrIdList();
        this.submitRequest();
      }
    },
    // 获取文件名
    getFileInfo: function (event) {
      this.file = event.target.files;
      console.log(this.file);
      this.fileDes = [];
      this.file.forEach((item) => {
        this.fileDes.push(item.name);
      });
    },
    // 获取当前的月份
    getLocalMonth: function () {
      let data = new Date();
      let year = data.getFullYear();
      let month = data.getMonth() + 1;
      if (month < 10) {
        month = "0" + month;
      } else {
        month = month + "";
      }
      this.localMonth = year + "-" + month;
    },
    // 提交接口
    submitRequest: function () {
      let paramData = new FormData();
      this.file.forEach((item) => {
        paramData.append("file", item);
      });

      paramData.append("dataName", this.inforName);
      paramData.append("dataDesc", this.inforDes);
      paramData.append("sourceTime", this.materialTime);
      paramData.append("dealerScope", this.scope);
      console.log(this.scope, 111);
      if (this.scope === "0") {
        paramData.append("dealerList", this.idList);
        console.log(1111, this.idList);
      }
      console.log(paramData.getAll("dataName"));
      this.$http
        .uploadFile("/firmsUpload", paramData)
        .then((res) => {
          if (res.data && res.data.code === 200) {
            this.tipModalFlag = true;
            this.tipModalText = "上传成功!";
          } else {
            alert("上传失败，请重试");
            console.log(res);
          }
        })
        .catch((err) => {
          alert("上传失败，请重试");
          console.log(err);
        });
    },
    // 获取所有资料名称
    getAllDataName: function () {
      this.$http({
        method: "post",
        url: "/firmsUploadList",
      })
        .then((res) => {
          if (res.data && res.data.code === 200) {
            (this.allDataNameList = []),
              res.data.data.forEach((item) => {
                this.allDataNameList.push(item.informationName);
              });
          } else {
            console.log(res);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取所有经销商信息接口
    getAllDlr: function (data = {}, flag, addBySelfFlag) {
      this.$http({
        method: "post",
        url: "/sys/agent/selectAgentInfoPage",
        data: data,
      })
        .then((res) => {
          console.log(res);
          this.tableData = [];
          let nowSum = this.sum;
          if (res.data && res.data.code === 200) {
            // created时，获取自定义添加datalist下拉框的值
            if (flag) {
              this.dlrList = [];
              let allDlrList = res.data.data;
              allDlrList.forEach((item) => {
                this.dlrList.push(item.dlrName);
                this.dlrList.push(item.dlrCode);
              });
            } else {
              // 整合数据， 主要目的是加一个 flag，在用户点击筛选的时候，好判断
              res.data.data.forEach((item) => {
                this.allDlr.push({
                  id: item.id,
                  dlrCode: item.dlrCode,
                  dlrName: item.dlrName,
                  localArea: item.localArea,
                  flag: true,
                });
              });
              // 去重
              let hash = {};
              this.allDlr = this.allDlr.reduce(function (item, next) {
                hash[next.id] ? "" : (hash[next.id] = true && item.push(next));
                return item;
              }, []);
              this.sum = this.allDlr.length;
              // 添加以后跳到最后一页
              this.currentPage = this.totalPage;
              let startData = (this.currentPage - 1) * this.pageSize;
              let endData = this.currentPage * this.pageSize;
              this.tableData = this.allDlr.slice(startData, endData);
              // 自定义添加  提示
              if (this.sum === nowSum && addBySelfFlag) {
                alert("该小组已在列表中，不用重复添加");
              }
            }
          } else {
            console.log(res);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取小组接口
    selectGroupList: function () {
      this.$http({
        method: "post",
        url: "/sys/group/selectGroupList",
        data: {},
      })
        .then((res) => {
          if (res.data && res.data.code === 200) {
            this.groupList = [];
            res.data.data.forEach((item) => {
              this.groupList.push({
                id: item.id,
                groupName: item.groupName,
                flag: true,
              });
            });
          } else {
            console.log(res);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取 所有区域  接口
    getAreaList: function () {
      this.$http({
        method: "post",
        url: "/sys/agent/selectAgentAreaInfoList",
      })
        .then((res) => {
          if (res.data && res.data.code === 200) {
            this.areaList = res.data.data;
          } else {
            console.log(res);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  mounted() {
    this.getLocalMonth();
  },
  created() {
    this.getAllDlr({}, true);
    this.getAllDataName();
    this.selectGroupList();
    this.getAreaList();
  },
};
</script>

<style scoped lang="less">
.upload_infor {
  form {
    border: 1px solid #ccc;
    padding: 10px;
  }
  .dataName {
    p {
      margin-left: 65px;
      font-size: 10px;
      color: rgb(206, 84, 84);
    }
  }
  .inforDes {
    margin: 10px 0 0 0;
    span {
      vertical-align: top;
      margin-right: 17px;
    }
    textarea {
      border: 1px solid #ccc;
      border-radius: 3px;
      color: #555555;
      font-size: 12px;
    }
  }
  .selectType {
    margin-top: 10px;
    margin-bottom: 10px;
    div {
      margin-left: 65px;
    }
  }
  .selectStyle {
    margin-left: 20px;
    margin-right: 20px;
    padding: 4px 6px;
    height: 28px;
    width: 144px;
    border: 1px solid #ccc;
    color: #555555;
    font-size: 12px;
  }
  .addByArea {
    margin: 10px 0 0 65px;
    display: flex;
    height: 28px;
    align-items: center;
    span {
      margin-right: 10px;
    }
    div {
      margin-right: 18px;
      height: 18px;
      input {
        width: 12px;
        height: 12px;
        vertical-align: middle;
        margin-top: -2px;
        border: 1px solid #ccc;
      }
      span {
        margin-left: 2px;
        height: 18px;
        line-height: 18px;
      }
    }
    button {
      height: 28px;
    }
  }
  .addByCustomize {
    margin: 10px 0 0 65px;
    button {
      height: 28px;
    }
    input {
      // background: url('../../img/search.svg') no-repeat center left;
      // background-size: 21px 25px;
      background-color: #fff;
    }
  }
  .addByGroup {
    margin: 10px 0 0 65px;
    display: flex;
    align-items: center;
    .selectBox {
      position: relative;
      margin-left: 17px;
      .group_select {
        width: 124px;
        height: 28px;
        border: 1px solid #ccc;
        background-color: #fff;
        padding: 0 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        p {
          font-size: 12px;
          height: 28px;
          line-height: 28px;
          color: #555555;
        }
        img {
          width: 16px;
          height: 16px;
        }
        &:hover {
          cursor: pointer;
        }
      }
      img {
        width: 144px;
        height: 28px;
        &:hover {
          cursor: pointer;
        }
      }
      .optionBox {
        position: absolute;
        top: 28px;
        left: 0;
        border: 1px solid #ccc;
        border-top: none;
        width: 142px;
        background-color: #fff;
        border-radius: 5px;
        ul {
          width: 144px;
          padding-bottom: 6px;
          display: flex;
          flex-direction: column;
          align-items: center;
          li {
            width: 132px;
            height: 28px;
            font-size: 12px;
            color: #555555;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #ccc;
            display: flex;
            justify-content: space-between;
            padding-right: 5px;
            img {
              width: 20px;
              height: 20px;
              &:hover {
                cursor: pointer;
              }
            }
          }
        }
      }
    }
    button {
      height: 28px;
    }
  }
  .table {
    margin-top: 10px;
  }
  .count {
    display: flex;
    justify-content: flex-end;
  }
  .uploadFile {
    display: flex;
    margin-top: 35px;
    height: 30px;
    align-items: center;
    p {
      margin-right: 20px;
      height: 20px;
      line-height: 20px;
    }
    .fileDes {
      margin-left: 20px;
      width: 500px;
      overflow: hidden;
      overflow: hidden; /* 超出一行文字自动隐藏 */
      text-overflow: ellipsis; /* 文字隐藏后添加省略号 */
      white-space: nowrap; /* 强制不换行 */
    }
    label {
      height: 30px;
      line-height: 30px;
      width: 56px;
      background-color: #0056a0;
      color: #fff;
      text-align: center;
      font-size: 14px;
      input {
        display: none;
      }
    }
  }
  .submitBtn {
    margin-top: 50px;
  }
}
.inputStyle {
  margin-left: 17px;
  width: 130px;
  height: 18px;
  line-height: 18px;
  padding: 4px 6px;
  border: 1px solid #ccc;
  color: #555555;
  font-size: 12px;
}
.focusStyle {
  border: 1px solid #ccc;
  line-height: 20px;
  color: #555555;
  outline: none;
}
.focusStyle:focus {
  animation: shadowAni 200ms linear forwards;
}
@keyframes shadowAni {
  0% {
    border-color: #cccccc;
    box-shadow: inset 0px 0px 0 #ccc;
  }
  100% {
    border-color: #75b9f0;
    box-shadow: 0px 0px 10px #75b9f0;
  }
}
</style>
