<template>
  <div class="app-container">
    <el-row :gutter="24" class="baseInfo">
      <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
        <el-card :bordered="false" dis-hover :padding="12">
          <div slot="header" class="acea-row row-between-wrapper">
            <span>总任务</span>
          </div>
          <div class="content" v-if="count">
                        <span class="content-number spBlock mb15"><count-to :start-val="0" :end-val="count.totalNum"
                                                                            :duration="2600"
                                                                            class="card-panel-num"/></span>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
        <el-card :bordered="false" dis-hover :padding="12">
          <div slot="header" class="acea-row row-between-wrapper">
            <span>今日加微数</span>
          </div>
          <div class="content" v-if="count">
                        <span class="content-number spBlock mb15"><count-to :start-val="0" :end-val="count.toDayAddNum"
                                                                            :duration="2600"
                                                                            class="card-panel-num"/></span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="外呼任务" prop="roboticId">
        <el-select v-model="queryParams.roboticId" filterable clearable>
          <el-option v-for="item in roboticList" :label="item.name" :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 label="销售" prop="roboticWxId">
        <el-select v-model="queryParams.roboticWxId" filterable clearable>
          <el-option v-for="item in accountList" :label="item.companyUserName + '-' + item.wxNickName"
                     :value="item.userId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否添加" prop="isAdd">
        <el-select v-model="queryParams.isAdd" clearable>
          <el-option label="否" :value="0"/>
          <el-option label="待通过" :value="2"/>
          <el-option label="是" :value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item label="加微时间" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          type="daterange"
          range-separator="至"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </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="['company:companyClient: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="['company:companyClient:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['company:companyClient:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="companyClientList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="外呼任务" align="center" prop="roboticName"/>
      <el-table-column label="销售" align="center" prop="wxNickName"/>
      <el-table-column label="个微昵称" align="center" prop="nickName"/>
      <el-table-column label="手机号码" align="center" prop="phone"/>
      <el-table-column label="话术" align="center" prop="dialogName"/>
      <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" prop="isAdd">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.isAdd == 0">否</el-tag>
          <el-tag type="warning" v-if="scope.row.isAdd == 2">待通过</el-tag>
          <el-tag type="success" v-if="scope.row.isAdd == 1">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="addTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.addTime, '{y}-{m}-{d}') }}</span>
        </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"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--            v-hasPermi="['company:companyClient:edit']"-->
          <!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['company:companyClient: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"
    />
    <qw-user-select @success="selectQwUserFun" ref="qwUserSelect"/>
    <!-- 添加或修改添加个微信账号对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="75%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="外呼任务" prop="roboticId">
          <el-select v-model="form.roboticId" filterable>
            <el-option v-for="item in roboticList" :label="item.name" :value="item.id"/>
          </el-select>
        </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="5">
              <el-button @click="openQwUserSelect(index)">
                选择企微({{ item.qwUserId ? item.qwUserId.length : 0 }})
              </el-button>
            </el-col>
            <el-col :span="5">
              <el-select v-model="item.wxDialogId" placeholder="话术" filterable>
                <el-option v-for="item in diaLogList" :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>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCompanyClient,
  addWxClient,
  addWxStatistics,
  getCompanyClient,
  delCompanyClient,
  addCompanyClient,
  updateCompanyClient,
  exportCompanyClient
} from "@/api/company/companyClient";
import {listAll as roboticListAll} from "@/api/company/companyVoiceRobotic";
import {listAll as dialogListAll} from '@/api/company/wxDialog';
import {listAll as accountListAll} from "@/api/company/companyAccount";
import {getDicts} from "@/api/system/dict/data";
import qwUserSelect from "@/views/components/QwUserSelect.vue";
import CountTo from "vue-count-to";

export default {
  name: "CompanyClient",
  components: {qwUserSelect, CountTo},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 添加个微信账号表格数据
      companyClientList: [],
      roboticList: [],
      diaLogList: [],
      accountList: [],
      levelList: [],
      thisQwUserIndex: 0,
      selectQwUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roboticWxId: null,
        nickAnme: null,
        avatar: null,
        phone: null,
        wxNo: null,
        isAdd: null,
        addTime: null,
        createUser: null
      },
      // 表单参数
      form: {},
      count: {},
      // 表单校验
      rules: {
        roboticId: [
          {required: true, message: "请选择任务", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    roboticListAll().then(e => {
      this.roboticList = e.data;
    })
    dialogListAll().then(e => {
      this.diaLogList = e.data;
    })
    accountListAll().then(e => {
      this.accountList = e.data;
    })
    getDicts("customer_intention_level").then(e => {
      this.levelList = e.data;
    })
    this.statis();
  },
  methods: {
    /** 查询添加个微信账号列表 */
    getList() {
      this.loading = true;
      listCompanyClient(this.getQueryData()).then(response => {
        this.companyClientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    statis() {
      addWxStatistics(this.getQueryData()).then(e => {
        this.count = e;
      })
    },
    getQueryData() {
      let form = JSON.parse(JSON.stringify(this.queryParams));
      if (form.time && form.time.length === 2) {
        form.beginTime = form.time[0];
        form.endTime = form.time[1];
      }
      delete form.time;
      return form;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        roboticId: null,
        roboticWxId: null,
        nickAnme: null,
        avatar: null,
        phone: null,
        qwUser: [],
        wxNo: null,
        isAdd: null,
        addTime: null,
        remark: null,
        createTime: null,
        createUser: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.statis();
      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
      getCompanyClient(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改添加个微信账号";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let list = [];
          this.form.qwUser.forEach(l => {
            if (l.qwUserId && l.qwUserId.length) {
              list = list.concat(l.qwUserId.map(e => {
                return {intention: l.intention, qwUserId: e, wxDialogId: l.wxDialogId}
              }))
            }
          })
          this.form.qwUserList = list;
          if (!this.form.qwUserList || this.form.qwUserList.length === 0) {
            this.msgError("请选者加微方案");
            return;
          }
          addWxClient(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 delCompanyClient(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function () {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有添加个微信账号数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportCompanyClient(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function () {
      });
    },
    addQwUser() {
      this.form.qwUser.push({});
    },
    removeQwUser(index) {
      this.form.qwUser.splice(index, 1)
    },
    openQwUserSelect(index) {
      this.thisQwUserIndex = index;
      this.$nextTick(() => {
        this.$refs.qwUserSelect.setRows(this.selectQwUserList[index]);
      })
    },
    selectQwUserFun(e) {
      this.form.qwUser[this.thisQwUserIndex].qwUserId = e.ids;
      this.selectQwUserList[this.thisQwUserIndex] = e.rows;
      this.$forceUpdate()
    },
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.baseInfo {
  margin-bottom: 30px;
}

.content {
  .card-panel-num {
    display: inline-block;
    font-size: 30px;
  }

  &-time {
    font-size: 14px;
    /*color: #8C8C8C;*/
  }
}
</style>
