<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入任务名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="机器人" prop="robot">
        <el-select v-model="queryParams.robot" filterable clearable>
          <el-option v-for="item in robotList" :label="item.name + '('+item.num+')'" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="话术" prop="dialogId">
        <el-select v-model="queryParams.dialogId" filterable clearable>
          <el-option v-for="item in dialogList" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:companyVoiceRobotic:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:companyVoiceRobotic:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:companyVoiceRobotic:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="mini"
          @click="updateStatusFun"
          v-hasPermi="['system:companyVoiceRobotic:list']"
        >更新状态
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roboticList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="id"/>
      <el-table-column label="任务名称" align="center" prop="name"/>
      <el-table-column label="三方名称" align="center" prop="taskName"/>
      <el-table-column label="三方ID" align="center" prop="taskId"/>
      <el-table-column label="机器人" align="center" prop="robot">
        <template slot-scope="scope">
          <p v-for="(item, index) in robotList"   v-if="scope.row.robot && scope.row.robot == item.id">{{item.name}}</p>
        </template>
      </el-table-column>
      <el-table-column label="话术" align="center" prop="dialogId">
        <template slot-scope="scope">
          <p v-for="(item, index) in dialogList"   v-if="scope.row.dialogId && scope.row.dialogId == item.id">{{item.name}}</p>
        </template>
      </el-table-column>
      <el-table-column label="加微方式" align="center" prop="dialogId">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.addType == 0">平均</el-tag>
          <el-tag v-if="scope.row.addType == 1">意向</el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="星期" align="center" prop="weekDay1">-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag v-for="(item, index) in weekList"   v-if="scope.row.weekDay1 && scope.row.weekDay1.indexOf(item.value) != -1">{{item.label}}</el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="开始时间" align="center" prop="startTime1"/>-->
<!--      <el-table-column label="结束时间" align="center" prop="endTime1"/>-->
      <el-table-column label="任务流程" align="center" width="230">
        <template slot-scope="scope">
          <div v-if="scope.row.taskFlow" v-model="scope.row.taskFlow.split(',')" class="flow-parent">
            <div v-for="(item, index) in scope.row.taskFlow.split(',')">
              <el-tag :type="scope.row.runTaskFlow != null && scope.row.runTaskFlow.split(',').indexOf(item) != -1 ? 'success' : 'warning'">{{ taskFlowMap[item] }}</el-tag>
              <i class="el-icon-arrow-right" v-if="index != 2"></i>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center">
        <template slot-scope="scope">
            <el-tag v-if="scope.row.taskStatus == 0">未启动</el-tag>
            <el-tag v-if="scope.row.taskStatus == 1" type="warning">执行中</el-tag>
            <el-tag v-if="scope.row.taskStatus == 2" type="danger">执行中断</el-tag>
            <el-tag v-if="scope.row.taskStatus == 3" type="success">执行完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="外呼状态" align="center">
        <template slot-scope="scope">
          <div v-loading="loadingStatus">
            <p v-if="statusObj.hasOwnProperty(scope.row.taskId)">
              <el-tag v-if="statusObj[scope.row.taskId].runningStatus == 0">未启动</el-tag>
              <el-tag v-if="statusObj[scope.row.taskId].runningStatus == 1">运行中</el-tag>
              <el-tag v-if="statusObj[scope.row.taskId].runningStatus == 2">已暂停</el-tag>
              <el-tag v-if="statusObj[scope.row.taskId].runningStatus == 3">已停止</el-tag>
            </p>
            <p v-if="!statusObj.hasOwnProperty(scope.row.taskId)"><el-tag>空</el-tag></p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="calleesOpen(scope.row.id)"
            v-hasPermi="['system:companyVoiceRobotic:list']"
          >客户列表</el-button>
          <el-button
            size="mini"
            type="text"
            @click="wxOpen(scope.row.id)"
            v-hasPermi="['system:companyVoiceRobotic:list']"
          >加微管理</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.taskStatus == 0"
            @click="taskRunFun(scope.row.id)"
          >启动任务</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="statusObj.hasOwnProperty(scope.row.taskId) && (statusObj[scope.row.taskId].runningStatus == 0 || statusObj[scope.row.taskId].runningStatus == 3)"
            @click="startRoboticFun(scope.row.taskId)"
            v-hasPermi="['system:companyVoiceRobotic:list']"
          >开启外呼任务</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="statusObj.hasOwnProperty(scope.row.taskId) && (statusObj[scope.row.taskId].runningStatus == 1 || statusObj[scope.row.taskId].runningStatus == 2)"
            @click="stopRoboticFun(scope.row.taskId)"
            v-hasPermi="['system:companyVoiceRobotic:list']"
          >停止任务</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:companyVoiceRobotic:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改机器人外呼任务对话框 -->
    <el-drawer size="75%" :title="title" :visible.sync="open" width="500px" append-to-body>
      <div class="app-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入任务名称"/>
          </el-form-item>
          <el-form-item label="机器人" prop="robot">
            <el-select v-model="form.robot" filterable>
              <el-option v-for="item in robotList" :label="item.name + '('+item.num+')'" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="话术" prop="dialogId">
            <el-select v-model="form.dialogId" filterable>
              <el-option v-for="item in dialogList" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="拨打客户" prop="userIds">
            <el-button @click="openSelect">选择客户({{ form.userIds ? form.userIds.length : 0 }})</el-button>
          </el-form-item>
          <el-form-item label="任务流程" prop="taskFlow">
            <draggable v-model="taskFlowList" @end="" class="flow-parent">
              <div class="flow-child" v-for="item in taskFlowList">
                <el-tag>{{ item.value }}</el-tag>
                <i class="el-icon-arrow-right"></i>
              </div>
            </draggable>
          </el-form-item>
          <el-form-item label="加微方式" prop="addType">
            <el-radio v-model="form.addType" :label="0">平均</el-radio>
            <el-radio v-model="form.addType" :label="1">意向</el-radio>
          </el-form-item>
          <el-form-item label="分配账号">
            <el-button @click="addQwUser">添加</el-button>
            <el-row :gutter="24" v-for="(item, index) in form.qwUser" style="margin-top: 5px">
              <el-col :span="5">
                <el-select v-model="item.intention" placeholder="意向等级" filterable clearable>
                  <el-option v-for="item in levelList" :label="item.dictLabel" :value="item.dictValue"/>
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button @click="openQwUserSelect(index)">选择企微({{ item.companyUserId ? item.companyUserId.length : 0 }})</el-button>
              </el-col>
              <el-col :span="5">
                <el-select v-model="item.wxDialogId" placeholder="话术" filterable>
                  <el-option v-for="item in wxDialogList" :label="item.name" :value="item.id"/>
                </el-select>
              </el-col>
              <el-col :span="3">
                <el-button type="danger" icon="el-icon-delete" circle @click="removeQwUser(index)"></el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="模式" prop="mode">
            <el-select v-model="form.mode">
              <el-option label="呼叫机器人后挂断" :value="7"/>
            </el-select>
          </el-form-item>
          <el-form-item label="呼叫倍率" prop="multiplier">
            <el-select v-model="form.multiplier">
              <el-option :value="1"/>
              <el-option :value="2"/>
              <el-option :value="3"/>
              <el-option :value="4"/>
              <el-option :value="5"/>
            </el-select>
          </el-form-item>
          <el-form-item label="自动重呼" prop="autoRecall">
            <el-radio v-model="form.autoRecall" :label="0">否</el-radio>
            <el-radio v-model="form.autoRecall" :label="1">是</el-radio>
          </el-form-item>
          <el-form-item label="重呼次数" prop="recallTimes" v-if="form.autoRecall == 1">
            <el-select v-model="form.recallTimes">
              <el-option label="不自动重呼" :value="0"/>
              <el-option :value="1"/>
              <el-option :value="2"/>
              <el-option :value="3"/>
              <el-option :value="4"/>
              <el-option :value="5"/>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>
    <customer-select @success="selectFun" ref="customer"/>
    <qw-user-select @success="selectQwUserFun" ref="qwUserSelect"/>

    <el-drawer title="呼叫客户列表" size="60%" :visible.sync="callees.show" width="800px" append-to-body>
      <el-table v-loading="callees.loading" :data="callees.list">
        <el-table-column label="电话号码" align="center" prop="phone"/>
        <el-table-column label="客户名称" align="center" prop="userName"/>
        <el-table-column label="客户ID" align="center" prop="userId"/>
        <el-table-column label="客户意向度" align="center">
          <template slot-scope="scope">
            <el-tag v-for="item in levelList" v-if="scope.row.intention == item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="openCustomer(scope.row.userId)"
            >客户信息详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="callees.total>0"
        :total="callees.total"
        :page.sync="callees.queryParams.pageNum"
        :limit.sync="callees.queryParams.pageSize"
        @pagination="getCalleesList"
      />
    </el-drawer>
    <el-drawer title="加微详情" size="60%" :visible.sync="wx.show" append-to-body>
      <el-table v-loading="wx.loading" :data="wx.list">
        <el-table-column label="意向等级" align="center" prop="intention"/>
        <el-table-column label="微信昵称" align="center" prop="wxNickName"/>
        <el-table-column label="微信号" align="center" prop="wxNo"/>
        <el-table-column label="手机号" align="center" prop="phone"/>
        <el-table-column label="员工名称" align="center" prop="companyUserName"/>
        <el-table-column label="话术" align="center" prop="dialogName"/>
        <el-table-column label="分配数量" align="center" prop="num"/>
        <el-table-column label="添加数量" align="center" prop="addNum"/>
      </el-table>

      <pagination
        v-show="wx.total>0"
        :total="wx.total"
        :page.sync="wx.queryParams.pageNum"
        :limit.sync="wx.queryParams.pageSize"
        @pagination="getWxList"
      />
    </el-drawer>
    <el-drawer size="75%" title="客户详情" :visible.sync="customerDetailShow" append-to-body>
      <customer-details ref="customerDetails" />
    </el-drawer>
  </div>
</template>

<script>
import {
  listRobotic,
  getRobotic,
  delRobotic,
  addRobotic,
  updateRobotic,
  exportRobotic,
  calleesList,
  statusList,
  startRobotic,
  stopRobotic,
  companyUserList,
  wxList,
  taskRun,
  getTypes
} from "@/api/company/companyVoiceRobotic";
import draggable from 'vuedraggable'
import { listAll } from '@/api/company/wxDialog';
import customerSelect from '@/views/crm/components/CustomerSelect.vue';
import qwUserSelect from '@/views/components/QwUserSelect.vue';
import customerDetails from "@/views/crm/components/customerDetails.vue";
import {clearTime} from "element-ui";
import {getDicts} from "@/api/system/dict/data";

export default {
  name: "Robotic",
  components: { draggable, customerDetails, customerSelect, qwUserSelect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      weekList: [
        {label: "星期一", value: 1},
        {label: "星期二", value: 2},
        {label: "星期三", value: 3},
        {label: "星期四", value: 4},
        {label: "星期五", value: 5},
        {label: "星期六", value: 6},
        {label: "星期日", value: 0},
      ],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      loadingStatus: true,
      // 总条数
      total: 0,
      // 机器人外呼任务表格数据
      roboticList: [],
      userTableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        taskName: null,
        taskId: null,
        robot: null,
        dialogId: null,
        mode: null,
        multiplier: null,
        autoRecall: null,
        recallTimes: null,
        cidGroupId: null,
        weekDay1: null,
        startTime1: null,
        endTime1: null,
        weekDay2: null,
        startTime2: null,
        endTime2: null,
        createUser: null
      },
      // 表单参数
      form: {},
      taskFlowList: [{key: "cellPhone", value: "外呼"}, {key: "sendMsg", value: "发短信"}, {key: "addWx", value: "加微"}],
      taskFlowMap: {cellPhone: "外呼", sendMsg: "发短信", addWx: "加微"},
      statusObj: {},
      levelList: {},
      robotList: [],
      dialogList: [],
      wxDialogList: [],
      qwUserList: [],
      selectQwUserList: [],
      thisQwUserIndex: 0,
      updateTime: null,
      customer: {
        show: false,
      },
      customerDetailShow: false,
      callees: {
        show: false,
        list: [],
        loading: false,
        total: 0,
        queryParams:{
          id: null,
          pageNum: 1,
          pageSize: 10,
        },
      },
      wx: {
        show: false,
        list: [],
        loading: false,
        total: 0,
        queryParams:{
          id: null,
          pageNum: 1,
          pageSize: 10,
        },
      },
      // 表单校验
      rules: {}
    };
  },
  created() {
    getTypes().then(e => {
      this.robotList = e.robot;
      this.dialogList = e.dialog;
    })
    listAll().then(e => {
      this.wxDialogList = e.data;
    })
    companyUserList().then(e => {
      this.qwUserList = e.data;
    })
    getDicts("customer_intention_level").then(e => {
      this.levelList = e.data;
    })
    this.getList();
  },
  methods: {
    /** 查询机器人外呼任务列表 */
    getList() {
      this.loading = true;
      listRobotic(this.queryParams).then(response => {
        this.roboticList = response.rows;
        this.roboticList.forEach(e => {
          if(e.weekDay1){
            e.weekDay = e.weekDay1.split(",")
          }
        })
        this.total = response.total;
        this.loading = false;
        this.updateStatusFun();
      });
    },
    updateStatusFun(){
      if(!this.roboticList){
        return;
      }
      this.loadingStatus = true;
      statusList(this.roboticList.map(e => e.taskId).join()).then(e => {
        this.loadingStatus = false;
        this.statusObj = e.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        taskName: null,
        taskId: null,
        robot: null,
        dialogId: null,
        mode: 7,
        multiplier: 3,
        autoRecall: 0,
        recallTimes: null,
        cidGroupId: null,
        weekDay1: null,
        startTime1: null,
        addType: 0,
        endTime1: null,
        weekDay2: null,
        startTime2: null,
        endTime2: null,
        createTime: null,
        qwUser: [],
        createUser: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加机器人外呼任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRobotic(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改机器人外呼任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.weekDay && this.form.weekDay.length > 0) {
            this.form.weekDay1 = this.form.weekDay.join(",")
          }
          let list = [];
          this.form.qwUser.forEach(l => {
            list = list.concat(l.companyUserId.map(e => {return {intention: l.intention, companyUserId: e,wxDialogId: l.wxDialogId}}))
          })
          this.form.qwUserList = list;
          if(!this.form.qwUserList || this.form.qwUserList.length == 0){
            this.msgError("请选者加微方案");
            return;
          }
          this.form.taskFlow = this.taskFlowList.map(e => e.key).join();
          if (this.form.id != null) {
            updateRobotic(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addRobotic(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除机器人外呼任务编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delRobotic(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function () {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有机器人外呼任务数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportRobotic(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function () {
      });
    },
    openSelect() {
      this.$refs.customer.setRows(this.form.userTableList);
    },
    openQwUserSelect(index) {
      this.thisQwUserIndex = index;
      this.$nextTick(() => {
        this.$refs.qwUserSelect.setRows(this.selectQwUserList[index]);
      })
    },
    selectFun(e) {
      this.form.userIds = e.ids;
      this.form.userNames = e.names;
      this.form.userTableList = e.rows;
      this.$forceUpdate()
    },
    selectQwUserFun(e) {
      this.form.qwUser[this.thisQwUserIndex].companyUserId = e.ids;
      this.selectQwUserList[this.thisQwUserIndex] = e.rows;
      this.$forceUpdate()
    },
    calleesOpen(id){
      this.callees.show = true;
      this.callees.queryParams.id = id;
      this.getCalleesList();
    },
    getCalleesList() {
      this.callees.loading = true;
      calleesList(this.callees.queryParams).then(response => {
        this.callees.list = response.rows;
        this.callees.total = response.total;
        this.callees.loading = false;
      });
    },
    wxOpen(id){
      this.wx.show = true;
      this.wx.queryParams.id = id;
      this.getWxList();
    },
    getWxList() {
      this.wx.loading = true;
      wxList(this.wx.queryParams).then(response => {
        this.wx.list = response.rows;
        this.wx.total = response.total;
        this.wx.loading = false;
      });
    },
    openCustomer(id) {
      this.customerDetailShow=true;
      this.$nextTick(() => {
        this.$refs.customerDetails.getDetails(id);
      })
    },
    startRoboticFun(id){
      startRobotic(id).then(e => {
        this.updateStatusFun();
      })
    },
    taskRunFun(id){
      taskRun({id}).then(e => {
        this.getList();
      })
    },
    stopRoboticFun(id){
      stopRobotic(id).then(e => {
        this.updateStatusFun();
      })
    },
    addQwUser(){
      this.form.qwUser.push({});
    },
    removeQwUser(index){
      this.form.qwUser.splice(index, 1)
    }
  }
};
</script>
<style>
.flow-parent{
  display: flex;
  flex-wrap: nowrap;
}
.flow-child{
  position: relative;
  width: 150px;
  cursor: move;
}
.flow-child:last-child i{
  display: none;
}
.flow-child:last-child::after{
  display: none;
}
.flow-child i{
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  position: absolute;
  font-weight: bold;
}
.flow-child::after{
  content: "";
  border-top: 1px solid #000;
  height: 1px;
  width: 50px;
  right: 26px;
  top: 50%;
  transform: translateY(-50%);
  position: absolute;
}
.sortable-ghost{
  //background: #FFF !important;
  background: rgb(217, 236, 255) !important;
}
</style>
