<template>
  <div class="box-center">
    <!-- 头 -->
    <div class="app-top">
      <div style="margin-left: 20px; display: flex">
        <el-button v-if="cus_sou_add" @click="editorinfo()" type="primary"
          >新增</el-button
        >
        <div
          style="margin-left: auto; margin-right: 10px"
          v-if="cus_sou_downLoad"
        >
          <el-button @click="downLoad">导出</el-button>
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div class="cen-tab">
      <el-table :data="tableData" stripe style="width: 100%" row-key="id">
        <el-table-column label="序号" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="sourceName" label="来源" align="center">
        </el-table-column>
        <el-table-column prop="customerCount" label="关联客户" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope" style="">
            <el-button type="text" @click="bianji(scope.row)">编辑</el-button>
            <el-button type="text" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      :title="editFlag ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      @close="$refs.ruleForm.resetFields()"
    >
      <el-form
        :model="ruleForm"
        label-position="labelPosition"
        :rules="ruleser"
        ref="ruleForm"
        label-width="140px"
        style="width: 60%; margin: 0 auto"
      >
        <el-form-item label="客户来源" prop="sourceName">
          <el-input
            v-model="ruleForm.sourceName"
            maxlength="8"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loadingFlag" @click="addForm"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="删除来源"
      :visible.sync="delVisible"
      @close="$refs.ruleForm.resetFields()"
    >
      <div style="text-align: center; margin-bottom: 20px">
        请将此来源的客户转移到以下来源
      </div>
      <el-form
        :model="ruleForm"
        label-position="labelPosition"
        :rules="ruleser"
        ref="ruleForm"
        label-width="140px"
        style="width: 60%; margin: 0 auto"
      >
        <el-form-item label="客户移至" prop="newSourceId">
          <el-select v-model="deleteParams.newSourceId" placeholder="请选择">
            <el-option
              v-for="item in delIdList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="
            delVisible = false;
            deleteParams.id = '';
          "
          >取 消</el-button
        >
        <el-button type="primary" :loading="loadingFlag" @click="deleteItem"
          >删除</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { exportMethodPost } from "@/util/util";
import Sortable from "sortablejs";
export default {
  data() {
    return {
      currentPage4: 1,
      value: "",
      input: "",
      tableData: [], // 客户来源列表
      multipleSelection: [],
      dialogVisible: false,
      loadingFlag: false,
      delVisible: false,
      orgType: localStorage.getItem("orgType"),
      ruleForm: {
        editFlag: "",
        id: "",
        sourceName: "", //
      },
      houseId: "",
      houseList: [],
      Page: 1,
      size: 10,
      words: "",
      total: 0,
      ruleser: {
        sourceName: [
          { required: true, message: "请填写客户来源", trigger: "blur" },
        ],
      },
      editFlag: false,
      paramsList: {
        // 列表入参
        id: "",
        sourceName: "", // 资源名称
        houseId:
          localStorage.getItem("houseId"), // 项目id
        sort: "", // 顺序
      },

      deleteParams: {
        // 删除入参
        id: "",
        newSourceId: "",
        houseId:
          localStorage.getItem("houseId"), // 项目id
      },
      delIdList: [], // 要转移的数据位置

      editParams: {
        // 编辑这一项
        id: "", //
        sourceName: "", //
      },
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  created() {
    this.cus_sou_add = this.permissions["cus_sou_add"];
    this.cus_sou_downLoad = this.permissions["cus_sou_downLoad"];
    this.cus_sou_del = this.permissions["cus_sou_del"];
    this.cus_sou_edit = this.permissions["cus_sou_edit"];
  },
  mounted() {
    this.rowDrop();
    this.getList();
  },
  methods: {
    /*判断类型选择使用方法*/
    addForm() {
      if (!this.editFlag) this.addCustomer();
      else this.editCustomer();
    },

    // 初始化提交变量
    initRuleForm() {
      this.ruleForm = {
        editFlag: "",
        id: "",
        sourceName: "", //
      };
    },

    // 确认添加
    addCustomer() {
      this.$refs.ruleForm.validate((valid) => {
        this.$api.api
          .setSourceAdd({
            sourceName: this.ruleForm.sourceName,
            houseId: this.paramsList.houseId,
          })
          .then((res) => {
            console.log(res);
            if (res.code == 10000) {
              this.dialogVisible = false;
              this.$message({
                message: res.message,
                type: "success",
              });
              this.initRuleForm();
              this.getList();
            } else {
              this.$message({
                message: res.message,
                type: "error",
              });
            }
          });
      });
    },

    // 编辑
    editCustomer() {
      this.$refs.ruleForm.validate((valid) => {
        this.$api.api.setSourceUpdate(this.ruleForm).then((res) => {
          console.log(res);
          if (res.code == 10000) {
            this.dialogVisible = false;
            this.$message({
              message: res.message,
              type: "success",
            });
            this.initRuleForm();
            this.getList();
          } else {
            this.$message({
              message: res.message,
              type: "error",
            });
          }
        });
      });
    },

    // 删除确认删除item
    deleteItem() {
      if (!this.deleteParams.newSourceId) {
        this.$message({
          message: "请选择客户移至",
          type: "error",
        });
        return;
      }
      this.$api.api.setSourceDel(this.deleteParams).then((res) => {
        console.log(res);
        this.delVisible = false;
        this.$message({
          message: res.message,
        });
        this.deleteParams.newSourceId = "";
        this.getList();
      });
    },

    // 获取列表
    getList() {
      this.$api.api.getSourceList(this.paramsList).then((res) => {
        if (res.code == 10000) {
          console.log(res, "list");
          this.tableData = res.data;
        }
      });
    },

    //行拖拽
    rowDrop() {
      const tbody = document.querySelector(".el-table__body-wrapper tbody");
      const _this = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          console.log(newIndex, oldIndex, "序号");
          const currRow = _this.tableData.splice(oldIndex, 1)[0];
          console.log(currRow);
          _this.tableData.splice(newIndex, 0, currRow);

          let list = _this.tableData.map((item) => {
            return item.id;
          });
          _this.$api.api
            .setSourceupDateSort({
              houseId: _this.paramsList.houseId,
              newSorts: list.join(","),
            })
            .then((res) => {
              console.log(res);
              if (res.code == 10000) {
                _this.$message({
                  message: res.message,
                  type: "success",
                });
                _this.getList();
              } else {
                _this.$message({
                  message: res.message,
                  type: "error",
                });
              }
            });
        },
      });
    },
    downLoad() {
      let obj = {
        houseId: this.houseId,
        words: this.words,
      };
      // exportMethodPost()
      exportMethodPost("autoSR/sensitivewords/export", "禁忌话术", obj);
    },
    houseChange() {
      this.Page = 1;
      this.words = "";
      this.taboofindbypagelist();
    },
    zkhousePage() {
      this.$api.api
        .findHouseByUser({
          orgType: localStorage.getItem("orgType"),
        })
        .then((res) => {
          this.houseList = res.data;
          if (localStorage.getItem("orgType") == 3) {
            this.houseId = localStorage.getItem("houseId");
          } else {
            this.houseId = res.data[0].id;
          }
          // this.houseId = res.data[0].id;
          this.taboofindbypagelist();
        });
    },
    taboofindbypagelist() {
      let obj = {
        current: this.Page,
        size: this.size,
        houseId: this.houseId,
        words: this.words,
      };
      this.$api.http.taboofindbypage(obj).then((res) => {
        console.log(res);
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
    },
    screening() {
      this.Page = 1;
      this.taboofindbypagelist();
    },
    //删除
    del(item) {
      this.delIdList = [];
      this.deleteParams.id = item.id;
      let arr = [];
      this.tableData.forEach((items) => {
        if (items.id != item.id) {
          arr.push({
            label: items.sourceName,
            value: items.id,
          });
        }
      });
      console.log(arr);
      this.delIdList = arr;
      this.delVisible = true;
    },
    //编辑
    bianji(row) {
      this.dialogVisible = true;
      this.ruleForm.sourceName = row.sourceName;
      this.ruleForm.id = row.id;
      this.editFlag = true;
    },

    editorinfo() {
      this.dialogVisible = true;
      this.editFlag = false;
      this.ruleForm.editFlag = "";
    },
    editor() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loadingFlag = true;
          if (this.editFlag == false) {
            this.$api.http
              .tabooadd({
                houseId: this.houseId,
                words: this.ruleForm.words,
              })
              .then((res) => {
                if (res.code == 0) {
                  setTimeout(() => {
                    this.loadingFlag = false;
                    console.log("防重");
                  }, 1);
                  this.dialogVisible = false;
                  this.$refs.ruleForm.resetFields();
                  this.Page = 1;
                  this.words = "";
                  this.taboofindbypagelist();
                } else {
                  this.$message.error(res.message);
                }
              });
          } else {
            this.$api.http
              .tabooupdate({
                id: this.ruleForm.id,
                words: this.ruleForm.words,
              })
              .then((res) => {
                if (res.code == 0) {
                  setTimeout(() => {
                    this.loadingFlag = false;
                    console.log("防重");
                  }, 1);
                  this.dialogVisible = false;
                  this.$refs.ruleForm.resetFields();
                  this.Page = 1;
                  this.words = "";
                  this.taboofindbypagelist();
                } else {
                  this.$message.error(res.message);
                }
              });
          }
        } else {
          return false;
        }
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.taboofindbypagelist();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.Page = val;
      this.taboofindbypagelist();
    },
  },
};
</script>

<style scoped="scoped" lang="scss" >
.box-center {
  width: 100%;
  padding: 15px;
  min-width: 1000px;
  padding-bottom: 100px;
}
.cen-tab {
  width: 100%;
  padding: 15px;
  background: #ffffff;
  margin-top: 15px;
}
.tophove {
  color: #ffffff;
  background: #2671e2;
}
.app-top {
  width: 100%;
  background: #ffffff;
  box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.04);
  border-radius: 4px;
  padding-top: 15px;
  padding-bottom: 15px;

  .app-titel {
    width: 100%;
    display: flex;
    align-items: center;
    .label {
      font-size: 14px;
      font-weight: 400;
      color: #32363d;
      line-height: 14px;
      margin-left: 15px;
    }
    .toptimeqhuan {
      height: 30px;
      background: #ffffff;
      display: flex;
      align-items: center;
    }
    .toptimeqhuan div {
      padding-left: 20px;
      padding-right: 20px;
      text-align: center;
      line-height: 30px;
      font-size: 14px;
      margin-right: 15px;
      border-radius: 4px;
      border: 1px solid #e0e0e0;
    }
  }
}
</style>
