<template>
  <div class="app-container">
    <div v-show="!isShowAddRule">
      <el-page-header @back="goBack" :content="contentTitle"></el-page-header>
      <!-- <el-divider></el-divider> -->

      <el-card shadow="never" style="margin-top: 20px">
        <div slot="header" class="clearfix">
          <span>规则基本信息</span>
        </div>
        <el-form label-position="right" label-width="100px" size="small">
          <el-form-item label="规则名称">
            <el-input
              v-model="ruleTitle"
              placeholder="请输入规则名称"
              style="width: 600px"
            ></el-input>
          </el-form-item>
          <el-form-item label="客服成员">
            <div class="custom-alert">
              <i class="el-icon-message-solid"></i
              >以下客服成员的新客户触发了规则后,
              将在侧边栏快捷回复提醒该规则的内容。
            </div>
            <div style="margin-top: 20px">
              <el-button
                icon="el-icon-plus"
                type="primary"
                plain
                @click="replaceCustomerService"
                >更换客服</el-button
              >
              <span class="common-text" style="margin-left: 10px"
                >可添加多个企业客服成员进行统一话术回复</span
              >
            </div>
            <div class="users">
              <!-- <div class="it" v-for="(item, index) in customList" :key="index"> -->
              <div
                class="it"
                v-for="(item, index) in selectCustomerList"
                :key="index"
              >
                <!-- <img :src="item.avatar" alt="" /> -->
                <img :src="squareUrl" alt="" />
                <span>{{ item.name }}</span>
                <i
                  class="el-icon-circle-close close"
                  @click="delCustomer(item,index)"
                ></i>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card shadow="never" style="margin-top: 20px">
        <div slot="header" class="clearfix">
          <span>设置推送周期及内容</span>
        </div>
        <div>
          <div class="common-text">
            设置规则后将会通过 [知客提醒] 提醒员工发推送内容
          </div>
          <div style="margin: 10px 0">
            <el-button
              icon="el-icon-plus"
              type="primary"
              plain
              size="small"
              @click="addRule('add')"
              >添加规则</el-button
            >
          </div>
          <div class="bottom-content">
            <div
              class="item"
              v-for="(item, index) in pushContentList"
              :key="index"
            >
              <div class="title">
                客户添加企业微信客服当天, {{ item.pushMin }}分钟后推送消息【{{
                  item.taskName
                }}】
              </div>
              <div class="wrap">
                <div class="tips">发送内容（共1条）</div>
                <div class="content">
                  <div v-if="item.sendType === 1||item.sendType === 5" class="text">
                    {{ item.sendText }}
                  </div>
                  <el-image
                    v-else-if="item.sendType === 2"
                    class="img"
                    :src="item.sendFile"
                  ></el-image>
                  <video
                    v-else-if="item.sendType === 3"
                    class="video"
                    :src="item.sendFile"
                    controls
                  ></video>
                  <div
                    v-else-if="item.sendType === 4"
                    class="box1"
                    @click="openWeb(item.sendFile)"
                  >
                    <div class="left">
                      <!-- <div class="name ellipsis">{{ item.webName }}</div>
                      <div class="desc ellipsis-2">{{ item.webDesc }}</div> -->
                      <div class="name ellipsis">{{ item.PageTitle }}</div>
                      <div class="desc ellipsis-2">{{ item.description }}</div>
                    </div>
                    <img :src="item.sendFile" alt="" />
                  </div>

                  <!-- <div v-else-if="item.sendType === 5" class="box2">
                    <img :src="item.sendFile" alt="" />
                    <div class="name ellipsis">{{ item.fileTitle }}</div>
                  </div> -->
                  <div v-else-if="item.sendType === 6" class="box1">
                    <div class="left">
                      <div class="name ellipsis">{{ item.sendFileName }}</div>
                    </div>
                    <!-- <img :src="item.sendFile" alt="" /> -->
                    <img
                      src="@/assets/common/word.png"
                      v-if="checkFileType(item.sendFile) == 'word'"
                    />
                    <img
                      src="@/assets/common/excel.png"
                      v-if="checkFileType(item.sendFile) == 'excel'"
                    />
                    <img
                      src="@/assets/common/ppt.png"
                      v-if="checkFileType(item.sendFile) == 'ppt'"
                    />
                    <img
                      src="@/assets/common/pdf.png"
                      v-if="checkFileType(item.sendFile) == 'pdf'"
                    />
                  </div>
                </div>
              </div>
              <div class="btns">
                <div class="btn" @click="addRule('edit', item,index)">
                  <i class="el-icon-edit"></i>编辑
                </div>
                <div class="btn" @click="delRule(item, index)">
                  <i class="el-icon-delete"></i>删除
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <div class="page-footer">
        <div class="footer" :class="classObj">
          <el-button
            type="primary"
            @click="submitForm"
            :loading="formLoading"
            >{{ formLoading ? "提交中 ..." : "提 交" }}</el-button
          >
          <el-popconfirm
            title="确定关闭吗？"
            @onConfirm="goBack"
            style="margin-left: 10px"
          >
            <el-button slot="reference">关 闭</el-button>
          </el-popconfirm>
        </div>
      </div>
    </div>

    <SopRuleAdd
      :listItem="addRuleItem"
      v-if="isShowAddRule"
      @backListFormDetail="backList"
      @sopRuleAdd="sopRuleAdd"
    />

    <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"
                   @click="pushCustomer(item, index)"
                >
                  <div style="text-align:center;cursor:pointer">
                    <el-avatar
                      shape="square"
                      :size="30"
                      :src="squareUrl"
                    ></el-avatar>
                    <span style="padding-left: 20px;line-height: 30px">{{ 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="[
                      item.checked ? 'el-icon-success' : 'el-icon-circle-check',
                      'iconClass',
                    ]"
                    :style="item.checked ? 'color:#377cfd!important' : ''"
                   
                  ></i>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="11">
          <el-card :body-style="{ padding: '0px' }">
            <div style="padding: 14px">
              <span>已选数量:{{ selectCustomerList.length }}</span>
              <div style="padding-top: 30px; height: 530px">
                <div
                  class="customerList"
                  v-for="(item, index) in selectCustomerList"
                  :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 { getToken } from "@/utils/auth";
import { delSopTask } from "@/api/marketing";
import SopRuleAdd from "@/views/marketing/components/sop-rule-add";
import {
  getDepartmentTree,
  getStaffList,
  addRules,
  editSopRule,
  getSopDetal,
} from "@/api/marketing";

export default {
  components: {
    SopRuleAdd,
  },
  data() {
    return {
      headerTitle:"", // 新增或者编辑
      contentTitle:"", // header标题
      customerIdList: [], // 客服列表
      workerIds: [], // 客服id列表
      currentIndex: "",
      treeId: "",
      websitId: "",
      squareUrl:
        "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
      customerServiceList: {}, // 更换客服列表
      customerServiceListRules: {}, // 更换客服列表检验
      customerList: [], // 客服列表
      selectCustomerList: [], // 已选客服列表
      staff: "", // 员工姓名
      departmentTree: [], //部门树
      departmentValue: "", // 已选部门
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: { "x-token": getToken() },
      customerServiceShow: false, // 更换客服弹窗
      editId: null,
      isEdit: false,
      formLoading: false,
      ruleTitle: "",
      customList: [],
      pushContentList: [],
      isShowAddRule: false,
      addRuleItem: null,
    };
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar;
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened,
      };
    },
  },
  created() {
    const { id ,type} = this.$route.query;
    console.log(type)
    this.headerTitle=type
    this.isEdit = id ? true : false;
    this.editId = id;
    if (this.isEdit) {
      this.getSopDetal(id);
    }
    this.getDepartmentTree();
    if(type=='add'){
      this.contentTitle='新增个人SOP'
    }else{
       this.contentTitle='编辑个人SOP'
    }
  },
  methods: {
    // 检查文件类型
    checkFileType(url) {
      if (!url) return "";
      const fileSuffix = url.substring(url.lastIndexOf(".") + 1);
      const wordList = ["doc", "docx", "dot", "wps", "wpt"];
      const excelList = ["xls", "xlsx", "xlt", "et", "ett"];
      const pptList = ["ppt", "pptx", "dps", "dpt", "pot", "pps"];
      const pdfList = ["pdf"];

      if (wordList.indexOf(fileSuffix) >= 0) {
        return "word";
      } else if (excelList.indexOf(fileSuffix) >= 0) {
        return "excel";
      } else if (pptList.indexOf(fileSuffix) >= 0) {
        return "ppt";
      } else if (pdfList.indexOf(fileSuffix) >= 0) {
        return "pdf";
      } else {
        return "";
      }
    },
    // 个人sop-删除任务
    delRule(item, index) {
      console.log(item);
      if (item.id) {
        delSopTask({ id: item.id }).then((res) => {
          console.log(res);
          this.getSopDetal(this.editId);
        });
      }
      this.pushContentList.splice(index, 1);
    },

    // 个人sop-修改规则
    editSopRule() {
      console.log(this.customerIdList);
      if (this.customerIdList !== []) {
        const params = {
          id: this.editId,
          ruleName: this.ruleTitle, // 规则名称
          workerIds: this.workerIds, // 客服ID，多个
          // sopPushTaskData:this.pushContentList
          sopPushTaskData: this.pushContentList,
        };
        editSopRule(params).then((res) => {
          console.log(res);
          if (res.code === 200) {
            this.$router.go(-1);
          }
        });
      }
    },

    // 获取详情
    getSopDetal(id) {
      getSopDetal({ id }).then((res) => {
        console.log(res);
        this.ruleTitle = res.data.ruleName;
        this.selectCustomerList = res.data.enterpriseWechatWorkers;
        this.pushContentList = res.data.sopPushTask;
        // this.selectCustomerList = res.data.enterpriseWechatWorkers.map(
        //   (item) => {
        //     return item.name;
        //   }
        // );
        this.workerIds = res.data.enterpriseWechatWorkers.map((item) => {
          return item.id;
        });

        console.log(this.selectCustomerList);
        console.log('已有客服id的列表',this.workerIds);
       
        console.log(this.pushContentList);

        const params = {
          pageNo: 1,
          pageSize: 10,
          adminWebsitId: id,
        };
        this.getStaffList(params);
      });
    },
    // 添加规则子组件
    sopRuleAdd(item) {
        this.isShowAddRule = false;
      console.log(item);
      this.pushContentList.push(item);
      console.log(this.pushContentList);
    },
    // 新增规则
    addRules() {
      console.log("新增规则");

      const params = {
        // 客服ID，任务，多个

        ruleName: this.ruleTitle, // 规则名称
        // "workerIds": this.customerIdList, // 客服ID，多个
        workerIds: this.customerIdList, // 客服ID，多个
        // sopPushTaskData:this.pushContentList
        sopPushTaskData: this.pushContentList,
        // sopPushTaskData: [
        //   {
        //     pushDay: "", // 几天后提醒
        //     pushDayMin: "", // 几点发送 格式（03:00）
        //     pushMin: "", // 分钟后提醒发送
        //     pushType: "", // 1当天 2自定义
        //     sendAppid: "", // 小程序appid
        //     sendFile: "", // 发送图片/视频/文件
        //     sendFileName: "", // 文件标题
        //     sendText: "", // 发送内容
        //     sendType: "", // 1文本 2图片 3短视频 4网页 5文件 6小程序
        //     sendUrl: "", // 地址路径
        //     sendUrlName: "", // 标题
        //     status: "", // 1 开启 0关闭
        //     taskName: "", // 任务名称
        //     type: "", // 1客户添加时间 2标签 3客户生日
        //     updateTime: "", // 修改时间
        //     tags: [
        //       {
        //         groupName: "", // 标签组名称
        //         name: "", // 标签
        //       },
        //     ],
        //   },
        // ],
      };
      addRules(params)
        .then((res) => {
          console.log(res);
          if (res.code === 200) {
            this.$router.go(-1);
          }
        })
        .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);
    },
    // 选择部门
    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);
      
    },
    // 获取部门树
    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(() => {});
    },
    // 获取成员列表
    getStaffList(params) {
      // const params={
      //   pageNo:1,
      //   pageSize:10,
      //   adminWebsitId:this.treeId,
      //   websitId: this.websitId
      // }
      getStaffList(params)
        .then((res) => {
          console.log(res);
          res.data.records.forEach((it) => {
            it.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.selectCustomerList.length;j++){
              if(this.customerList[i].id==this.selectCustomerList[j].id){
                this.customerList[i].checked=true
              }
            }
          }
        })
        .catch(() => {});
    },
    // 增加客服
    pushCustomer(item, index) {
       console.log(this.customerList)
      item.checked = true;
       console.log(this.customerList)
      console.log('点击增加客服',item, index);
      this.currentIndex = index;
      if (this.workerIds.indexOf(item.id) == -1) {
        this.workerIds.push(item.id);
      }

      console.log('已选的客服id列表',this.workerIds)
      console.log('全部客服列表',this.customerList)
      const selectCustomer=this.selectCustomerList.map((it)=>{
        return it.name
      })
      console.log('全部客服名称列表',selectCustomer)
      console.log('被添加的客服名称',item.name)
      const isTrue=selectCustomer.indexOf(item.name) == -1
      console.log(isTrue)
       if(selectCustomer.indexOf(item.name) == -1){
        
         this.selectCustomerList.push(item)
         console.log(this.selectCustomerList)
       }
     

     
    },
    // 更换客服
    replaceCustomerService() {
      console.log("更换客服");

     if(this.headerTitle=='edit'){
         this.getSopDetal(this.editId)
     }
     
     
      this.customerServiceShow = true;
    },
    // 删除客服
    delCustomer(item,index) {
      this.checked = false;
      this.selectCustomerList.splice(index, 1);
      console.log("删除客服",item,index);
      this.workerIds.splice(index, 1);
      console.log(this.workerIds);
      this.customerList.forEach(it=>{
        if(it.id==item.id){
          it.checked=false
        }
      })

    },
    // 取消更换客服弹窗
    cancelAddChildForm() {
      this.customerServiceShow = false;
      // this.$refs.addChildForm.resetFields();
      // this.customerList=[]
      this.currentIndex = "";
      this.departmentValue = "";
      this.staff=""
    },
    // 提交更换客服弹窗
    submitAddChildForm() {
      console.log("提交选择客服");
      this.customerServiceShow = false;
      // this.customerList=[]
      this.currentIndex = "";
      this.departmentValue = "";
      this.staff=""
    },
    // 返回主页
    goBack() {
      this.$router.go(-1);
    },

    

    // 打开网页
    openWeb(url) {
      window.open(url);
    },

    // 添加编辑规则
    addRule(type, item,index) {
      console.log(type, item,index);
      this.isShowAddRule = true;
      this.addRuleItem = item;
      if(type=='edit'){
           this.addRuleItem.index=index
      }
     
      console.log(this.addRuleItem)
    },

    submitForm() {
      if (!this.ruleTitle) {
        return this.$errorMsg("请输入规则名称");
      }
      if (!this.selectCustomerList || this.selectCustomerList.length < 1) {
        return this.$errorMsg("请添加客服");
      }
      if (!this.pushContentList || this.pushContentList.length < 1) {
        return this.$errorMsg("请添加规则");
      }

      if (this.isEdit) {
        this.editSopRule();
      } else {
        this.addRules();
      }
    },

    backList(item) {
      this.isShowAddRule = false;
      console.log(item)
      console.log(this.pushContentList)
     this.pushContentList[item.index]=item
      
  
      
       console.log(this.pushContentList)
     
      
    },
  },
};
</script>

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

.el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}
.custom-alert {
  width: 600px;
  color: #377cfd;
  padding: 0 16px;
  border-radius: 2px;
  background-color: rgb(235, 245, 255);
  border: 1px solid rgb(230, 240, 255);
  i {
    margin-right: 4px;
  }
}
.common-text {
  font-size: 14px;
  color: #666;
}
::v-deep .el-card__header {
  font-weight: 600;
}
.page-footer {
  height: 70px;
  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 1;
    width: 100%;
    background: #fff;
    padding: 15px 40px;
    box-sizing: border-box;
    transition: all 0.28s;
    text-align: right;
    box-shadow: 0 2px 5px 0 rgb(0 0 0 / 50%), 0 2px 5px 0 rgb(0 0 0 / 10%);
    &.hideSidebar {
      margin-left: 54px;
      width: calc(100vw - 54px);
    }
    &.openSidebar {
      margin-left: 210px;
      width: calc(100vw - 210px);
    }
  }
}
.users {
  display: flex;
  align-items: center;
  margin-top: 20px;
  .it {
    margin-right: 20px;
    margin-bottom: 10px;
    padding: 0 10px;
    border: 1px solid rgb(228, 231, 237);
    border-radius: 2px;
    display: flex;
    align-items: center;
    height: 34px;
    position: relative;
    img {
      width: 26px;
      height: 26px;
      margin-right: 6px;
      border-radius: 2px;
    }
    span {
      color: rgba(0, 0, 0, 0.45);
    }
    .close {
      position: absolute;
      top: -10px;
      right: -10px;
      background: #fff;
      color: #666;
      font-size: 18px;
      cursor: pointer;
    }
  }
}
.bottom-content {
  .item {
    position: relative;
    margin-bottom: 20px;
    .btns {
      position: absolute;
      bottom: 0;
      left: 660px;
      display: flex;
      flex-direction: column;
      .btn {
        padding: 4px;
        margin-top: 5px;
        cursor: pointer;
        border-radius: 2px;
        background-color: #f2f2f2;
        font-size: 12px;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .title {
      color: #222;
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 10px;
    }
    .wrap {
      padding: 16px;
      background: #f2f2f2;
      width: 650px;
      .tips {
        font-size: 14px;
        margin-bottom: 10px;
      }
      .content {
        padding: 10px;
        background: #fff;
        .text {
          font-size: 14px;
          color: #666;
        }
        .img {
          width: 200px;
          height: 200px;
          display: block;
        }
        .video {
          width: 200px;
          height: 200px;
          display: block;
        }
        .box1 {
          display: flex;
          padding: 10px;
          align-items: center;
          border: 1px solid #e4e7ed;
          cursor: pointer;
          .left {
            flex: 1;
            margin-right: 10px;
            .name {
              color: #222;
              font-weight: 600;
            }
            .desc {
              color: #999;
              font-size: 12px;
              margin-top: 10px;
            }
          }
          img {
            width: 40px;
            height: 40px;
            display: block;
          }
        }
        .box2 {
          display: flex;
          padding: 10px;
          align-items: center;
          border: 1px solid #e4e7ed;
          cursor: pointer;
          img {
            width: 40px;
            height: 40px;
            display: block;
          }
          .name {
            flex: 1;
            color: #222;
            font-weight: 600;
            margin-left: 10px;
          }
        }
      }
    }
  }
}
.el-icon-circle-check:before{
  line-height: 30px;
}
.el-icon-success:before{
   line-height: 30px;
}
</style>