<template>
  <div class="app-container">
    <!-- 筛选条件 -->
    <div class="screen-container">
      <el-form
        ref="screenForm"
        :model="screenForm"
        label-width="70px"
        size="small"
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :xs="18" :sm="12" :lg="12">
            <el-form-item label="规则名称" prop="keyword">
              <el-input
                v-model="screenForm.keyword"
                placeholder="请输入规则名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="6" :sm="6" :lg="6">
            <el-form-item label="">
              <el-button size="small" @click="resetScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitScreenForm"
                >搜索</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="mymain-container" style="margin-top: 0">
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="addOrEdit('add')"
            >新增</el-button
          >
        </div>
      </div>

      <div class="table">
        <el-table
          v-loading="listLoading"
          :data="dataList"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          stripe
        >
          <el-table-column
            align="center"
            label="操作"
            width="200"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="toCustomer(scope.row)"
                >添加客服</el-button
              >
              <el-button type="text" @click="toDetail(scope.row.id)"
                >详情</el-button
              >
              <el-button type="text" @click="addOrEdit('edit', scope.row.id)"
                >编辑</el-button
              >
              <el-popconfirm
                style="margin-left: 10px"
                title="确定删除吗？"
                @onConfirm="handleDelete(scope.row.id)"
              >
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="规则名称"
            prop="ruleName"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="客服成员"
            prop="enterpriseWechatWorkers"
            min-width="160"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-tag
                v-for="(item, index) in scope.row.enterpriseWechatWorkers"
                :key="index"
                size="small"
                style="margin-right: 10px"
                >{{ item.name }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="状态"
            prop="status"
            min-width="100"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                @change="stautsSwitch(scope.row.status, scope.row)"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>

              {{ scope.row.status == 1 ? "已启用" : "已关闭" }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="创建人"
            prop="createBy"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="创建时间"
            prop="createTime"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
        </el-table>
      </div>

      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 添加客服 -->
    <el-dialog
      title="添加客服"
      :visible.sync="customerServiceShow"
      :show-close="false"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addChildForm"
        :model="customerServiceList"
        :rules="customerServiceListRules"
        label-position="left"
      >
        <el-form-item label="部门" prop="">
          <el-col :span="10">
            <el-select v-model="departmentValue" placeholder="请选择部门">
              <el-option
                v-for="item in departmentTree"
                :key="item.id"
                :label="item.name"
                :value="item.name"
                @click.native="departmentChangeFn(item)"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>

        <el-form-item label="员工" prop="">
          <el-col :span="10">
            <el-input
              v-model="staff"
              placeholder="请输入员工"
              @change="selectStaff"
            ></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <el-row>
        <el-col :span="11" style="margin-right: 10px">
          <el-card :body-style="{ padding: '0px' }">
            <div style="padding: 14px">
              <span>客服数量:{{ customerList.length }}</span>
              <div style="padding-top: 30px; height: 530px">
                <div
                  class="customerList"
                  v-for="(item, index) in customerList"
                  :key="index"
                >
                  <div>
                    <el-avatar
                      shape="square"
                      :size="30"
                      :src="squareUrl"
                    ></el-avatar>
                    <span style="padding-left: 20px">{{ item.name }}</span>
                  </div>
                  <!-- <el-image
      style="width: 30px; height: 30px"
      :src="item.qrCode2"
      :fit="fit"></el-image> -->

                  <!-- <el-radio
                    v-model="customerList.item"
                    :label="item.name"
                    @change="pushCustomer(item.name)"
                  ></el-radio> -->
                  <!-- #377cfd!important -->
                  <!-- <i class="el-icon-circle-check" :style="{'font-size':'20px',color:'this.iconActive'}" @click="pushCustomer(item)"></i> -->
                  <!-- <i
                    :class="[
                      index === currentIndex
                        ? 'el-icon-success'
                        : 'el-icon-circle-check',
                      'iconClass',
                    ]"
                    :style="
                      index === currentIndex ? 'color:#377cfd!important' : ''
                    "
                    @click="pushCustomer(item, index)"
                  ></i> -->
                   <i
                    :class="[
                      item.checked
                        ? 'el-icon-success'
                        : 'el-icon-circle-check',
                      'iconClass',
                    ]"
                    :style="
                      item.checked? 'color:#377cfd!important' : ''
                    "
                    @click="pushCustomer(item, index)"
                  ></i>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="11">
          <el-card :body-style="{ padding: '0px' }">
            <div style="padding: 14px">
              <span>已选数量:{{ checkedWorkerList.length }}</span>
              <div style="padding-top: 30px; height: 530px">
                <div
                  class="customerList"
                  v-for="(item, index) in checkedWorkerList"
                  :key="index"
                >
                  <div>
                    <el-avatar
                      shape="square"
                      :size="30"
                      :src="squareUrl"
                    ></el-avatar>
                    <span style="padding-left: 20px">{{ item.name }}</span>
                  </div>
                  <i
                    class="el-icon-close"
                    style="font-size: 28px"
                    @click="delCustomer(item, index)"
                  ></i>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddChildForm">取 消</el-button>
        <el-button type="primary" @click="submitAddChildForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSopList,
  delSopRule,
  getDepartmentTree,
  getStaffList,
  editSopRule,
  addKeFu,
} from "@/api/marketing";

export default {
  data() {
    return {
      treeId: "",
      websitId: "",
      Ids:[], // 删除后的客服id
      checkedWorkerList: [], // 已选客服列表
      allWorkerIds: [], // 所有客服
      selectStatus: "", // 添加客服  状态
      hasId: "", // 添加客服 已添加的客服id列表
      status: "", // 列表 状态
      selectWorkerIds: "", // 添加客服id
      selectRuleName: "", // 添加客服规则名称
      selectSopPushTaskData: [], // 添加客服 多个规则
      workerIds: [], // 客服id列表
      customerIdList: [], // 添加客服id列表
      customerServiceShow: false, // 添加客服弹窗
      currentIndex: "",
      squareUrl:
        "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
      customerServiceList: {}, // 更换客服列表
      customerServiceListRules: {}, // 更换客服列表检验
      customerList: [], // 客服列表
      selectCustomerList: [], // 已选客服列表
      staff: "", // 员工姓名
      departmentTree: [], //部门树
      departmentValue: "", // 已选部门
      dataList: null, // 列表数据
      listLoading: false, // 列表加载loading
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      screenForm: {
        keyword: "",
      },
    };
  },

  created() {
    this.getList();
    this.getSopList();
    this.getDepartmentTree();
  },

  methods: {
    // 列表 状态
    stautsSwitch(item, row) {
      console.log(item, row);
      // this.status=row.status
      // console.log(this.status)
      const workerId = row.enterpriseWechatWorkers.map((item) => {
        return item.id;
      });
      console.log(workerId);
      const params = {
        status: row.status,
        id: row.id,
        ruleName: row.ruleName, // 规则名称
        workerIds: workerId, // 客服ID，多个
        // sopPushTaskData:this.pushContentList
        sopPushTaskData: row.sopPushTask,
      };
      editSopRule(params).then((res) => {
        console.log(res);
        this.getSopList();
      });
    },
    // 添加客服
    toCustomer(item) {
      console.log("添加客服", item);
      this.customerServiceShow = !this.customerServiceShow;
      this.selectWorkerIds = item.id;
      this.selectRuleName = item.ruleName;
      this.selectSopPushTaskData = item.sopPushTask;
      this.selectStatus = item.status;

      // 回显的客服id
      const hasId = item.enterpriseWechatWorkers.map((item) => {
        return item.id;
      });
      console.log("回显已选择的客服id", hasId);
      this.hasId = hasId;

      // console.log(item.enterpriseWechatWorkers)

      // 已选的客服列表
     
      //  item.enterpriseWechatWorkers.forEach(it=>{
      //   it.checked=false
      // })
       this.checkedWorkerList = item.enterpriseWechatWorkers;
      console.log(this.checkedWorkerList)
     
      // console.log(this.checkedWorkerList.length)
     
      
      



      // const hasCustomer = item.enterpriseWechatWorkers.map((item) => {
      //   return item.name;
      // });
      // console.log(hasCustomer)
      // this.selectCustomerList=hasCustomer
      // console.log(this.selectCustomerList);

      // 回显列表员工
      const params = {
        pageNo: 1,
        pageSize: 10,
        adminWebsitId: item.id,
      };
      this.getStaffList(params);
    },
    // 取消更换客服弹窗
    cancelAddChildForm() {
      this.customerServiceShow = false;
      // this.$refs.addChildForm.resetFields();
      // this.customerList=[]
      this.currentIndex = "";
      this.departmentValue = "";
      this.staff=""
    },

    // 获取部门树
    getDepartmentTree() {
      getDepartmentTree()
        .then((res) => {
          console.log(res);
          this.departmentTree = res.data[0].children;
          // this.departmentTree=res.data[0].children.map(item=>{
          //   return item.name
          // })
        })
        .catch(() => {});
    },
    // 选择部门
    departmentChangeFn(item) {
      console.log(item);
      this.treeId = item.id;
      this.websitId = item.websitId;
      console.log(this.treeId, this.websitId);
      const params = {
        pageNo: 1,
        pageSize: 10,
        adminWebsitId: this.treeId,
        websitId: this.websitId,
         keyword: this.staff,
      };
      this.getStaffList(params);
      // getStaffList(params)
      //   .then((res) => {
      //     console.log(res);
      //     this.customerList=res.data.records
      //     console.log( this.customerList)

      //   })
      //   .catch(() => {});
    },
    // 获取成员列表
    getStaffList(params) {
      // const params={
      //   pageNo:1,
      //   pageSize:10,
      //   adminWebsitId:this.treeId,
      //   websitId: this.websitId
      // }
      getStaffList(params)
        .then((res) => {
          console.log(res);
          //  // 给数组每个对象添加一个checked属性，默认为false
          res.data.records.forEach((item) => {
            item.checked = false;
          });
          this.customerList = res.data.records;
          console.log(this.customerList);
          for(let i=0;i<this.customerList.length;i++){
       for(let j=0;j<this.checkedWorkerList.length;j++){
         if(this.customerList[i].id==this.checkedWorkerList[j].id){
           this.customerList[i].checked=true
         }
       }
     }
       console.log(this.customerList)
          console.log(this.customerList.length)
         


        })
        .catch(() => {});
    },
    // 筛选员工
    selectStaff() {
      console.log(this.staff);
      const params = {
        pageNo: 1,
        pageSize: 10,
        keyword: this.staff,
         adminWebsitId:this.treeId, // 部门id
        websitId: this.websitId // 部门的websitId
      };
      this.getStaffList(params);
    },
    // 增加客服
    pushCustomer(item, index) {
      item.checked=true
      console.log("点击增加客服", item, index, "客服id列表", this.hasId);
      this.currentIndex = index;
      if (this.hasId.indexOf(item.id) == -1) {
        // this.customerIdList.push(item.id);
        this.hasId.push(item.id);
        console.log("增加客服后的客服id列表", this.hasId);
      }

      console.log(this.checkedWorkerList);

      const selectCustomerList = this.checkedWorkerList.map((it) => {
        return it.name;
      });
      console.log(selectCustomerList);

      if (selectCustomerList.indexOf(item.name) == -1) {
        // this.selectCustomerList.push(item.name);
        this.checkedWorkerList.push(item);
        console.log(this.checkedWorkerList);
      }
      // this.selectCustomerList.push(item.name);
      // console.log(this.selectCustomerList);
    },
    // 更换客服
    // replaceCustomerService() {
    //   console.log("更换客服");
    //   this.customerServiceShow = true;
    // },
    // 删除客服
    delCustomer(item, index) {
      item.checked=false
      console.log("删除客服", item, index);
      this.customerList.forEach(it=>{
        if(it.id==item.id){
          it.checked=false
        }
      })
    
    

      // 从已有的客服中删除
      this.checkedWorkerList.splice(index, 1);
      const delId= this.hasId.findIndex((items) => items.id == item.id)
      console.log(delId)
      //  this.hasId.splice(
      //   this.hasId.findIndex((items) => items.id == item.id),
      //   1
      // );
        this.hasId.splice(
      index,
        1
      );
      console.log("删除后的客服id", this.hasId);
    },
    // 取消更换客服弹窗
    cancelAddChildForm() {
      this.customerServiceShow = false;
      // this.$refs.addChildForm.resetFields();
      // this.customerList=[]
      this.currentIndex = "";
      this.departmentValue = "";
      this.staff=""
    },
    // 提交更换客服弹窗
    submitAddChildForm() {
      this.customerServiceShow = false;

      this.currentIndex = "";
      this.departmentValue = "";
      this.staff=""
      //   const params = {
      //   id:  this.selectWorkerIds,
      //   ruleName: this.selectRuleName,
      //   sopPushTaskData: this.selectSopPushTaskData ,
      //   status: this.selectStatus,
      //   workerIds: this.customerIdList,
      // };
      // addKeFu(params).then((res) => {
      //   console.log(res);
      //   this.getSopList();
      // });
     
      const params = {
        id: this.selectWorkerIds,
        ruleName: this.selectRuleName, // 规则名称
        workerIds: this.hasId, // 客服ID，多个
        // sopPushTaskData:this.pushContentList
        sopPushTaskData: this.selectSopPushTaskData,
      };
      editSopRule(params).then((res) => {
        console.log("修改sop规则", res);
        this.getSopList();
      });
    },

    // 个人sop-list
    getSopList() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        ruleName: this.screenForm.keyword,
      };
      getSopList(params).then((res) => {
        console.log("获取个人sop-list", res);
        this.dataList = res.data.records;
        console.log(this.dataList);
      });
    },
    getList() {
      // this.listLoading = true;
      // let params = {
      //   keyword: this.screenForm.keyword,
      //   pageNum: this.currentPage,
      //   pageSize: this.pageSize
      // }
      // getList(params).then(res => {
      //   this.dataList = res.data.records;
      //   this.listTotal = res.data.total;
      //   this.listLoading = false;
      // })
      // let dataList = [
      //   {id: 1, title: '测试数据1', content: '详细描述详细描述详细描述详细描述详细描述详细描述详细描述详细描述详细描述', file: 'a.xls'},
      //   {id: 2, title: '测试数据2', content: '详细描述详细描述详细描述详细描述详细描述详细描述详细描述详细描述'},
      //   {id: 3, title: '测试数据3', content: '详细描述详细描述详细描述详细描述详细描述详细描述详细描述'},
      // ]
      // // 给数组每个对象添加一个属性，默认为false
      // dataList.forEach(item => {
      //   item.selected = false;
      // });
      // this.dataList = dataList;
      // console.log(this.dataList)
    },

    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1;
      // this.getList();
      this.getSopList();
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields();
      this.currentPage = 1;
      // this.getList();
      this.getSopList();
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      // this.getList();
      this.getSopList();
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      // this.getList();
      this.getSopList();
    },

    // 操作 - 删除
    handleDelete(id) {
      console.log(id);
      delSopRule({ id: id }).then((res) => {
        console.log(res);
        this.getSopList();
      });

      // deleteStorage({storageId: id}).then(() => {
      //   this.getList();
      //   this.$successMsg();
      // })
    },

    // 新增
    addOrEdit(type, id) {
      if (type == "add") {
        this.$router.push({
          path: "/marketing/sop_add",
          query: {
            type,id
          },
        });
      } else {
        this.$router.push({
          path: "/marketing/sop_add",
          query: {

            type,id
          },
        });
      }
    },

    toDetail(id) {
      this.$router.push({
        path: "/marketing/sop_detail",
        query: {
          id,
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.top-tips {
  font-size: 14px;
  margin-bottom: 20px;
}
.iconClass {
  font-size: 20px;
}
.customerList {
  display: flex;
  justify-content: space-between;
  padding-bottom: 20px;
}
::v-deep .el-avatar {
  vertical-align: middle;
}
</style>