<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入任务名称" />
      <el-button v-permission="['GET /admin/campaign/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/campaign/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" label="任务名" prop="name" />

      <el-table-column align="center" label="任务类型" prop="type">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type==0 ? 'success' : 'error' ">{{ scope.row.type==0 ? '固定任务' : scope.row.type==1?'自定义条件筛选任务':'导入任务' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否只分配在线坐席" prop="isCsrOnline">
        <template slot-scope="scope">{{ filterBoolen(scope.row.isCsrOnline) }}</template>
      </el-table-column>

      <el-table-column align="center" label="是否自动分配" prop="isAutoAssigned">
        <template slot-scope="scope">{{ filterBoolen(scope.row.isAutoAssigned) }}</template>
      </el-table-column>

      <el-table-column align="center" label="任务数据筛选频次" prop="isNightRun">
        <template slot-scope="scope">{{ filterRun(scope.row.isNightRun) }}</template>
      </el-table-column>

      <el-table-column align="center" label="是否启用" prop="deleted">
        <template slot-scope="scope">
          <el-tag :type="scope.row.deleted ? 'success' : 'error' ">{{ scope.row.deleted ? '停用' : '启用' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="任务分配时间段" prop="assignedStart">
        <template slot-scope="scope">
          <el-tag :type="scope.row.assignedStart!=null ? 'success' : 'error' ">{{ scope.row.assignedStart!=null?(scope.row.assignedStart+'~'+scope.row.assignedEnd):'未设置' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="left" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/campaign/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.deleted==false" v-permission="['POST /admin/campaign/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">停用</el-button>
          <el-button v-else v-permission="['POST /admin/campaign/delete']" type="info" size="mini" @click="handleDelete(scope.row)">启用</el-button>
          <el-button v-if="scope.row.deleted==false" v-permission="['POST /admin/campaign/assigned','POST /admin/campaign/read']" type="success" size="mini" @click="handleAssigned(scope.row)">分配</el-button>

        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="150px" style="width: 600px; margin-left:50px;">
        <el-form-item label="任务标题" prop="name">
          <el-input v-model.trim="dataForm.name" placeholder="请输入任务名称" />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="dataForm.type" :disabled="disabled">
            <el-radio :label="0">固定任务</el-radio>
            <el-radio :label="1">自定义条件筛选任务</el-radio>
            <el-radio :label="2">导入任务</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否只分配在线客服" prop="isCsrOnline">
          <el-radio-group v-model="dataForm.isCsrOnline">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否自动分配" prop="isAutoAssigned">
          <el-radio-group v-model="dataForm.isAutoAssigned" @change="assignedChange">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="任务分配时间段" prop="assignedStart">
          <el-select v-model="dataForm.assignedStart" :disabled="!dataForm.isAutoAssigned">
            <el-option v-for="type in assigedOptions" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
          <el-select v-model="dataForm.assignedEnd" :disabled="!dataForm.isAutoAssigned">
            <el-option v-for="type in assigedOptions" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="任务数据筛选频次" prop="isNightRun">
          <el-radio-group v-model="dataForm.isNightRun">
            <el-radio :label="true">每晚一次</el-radio>
            <el-radio :label="false">实时</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="自定义SQL" prop="customSql">
          <el-input v-model="dataForm.customSql" type="textarea" placeholder="如需填写此字段 请与研发或产品协助" />
        </el-form-item>

        <el-form-item label="话术" prop="faq">
          <el-input v-model="dataForm.faq" type="textarea" />
        </el-form-item>

        <el-form-item label="任务描述" prop="remark">
          <el-input v-model="dataForm.remark" type="textarea" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 任务分配 -->
    <el-dialog :title="assignedCampaignName" :visible.sync="dialogAssignedVisible">
      <el-form ref="dataForm" :rules="rules" status-icon label-position="left" label-width="150px" style="width: 600px; margin-left:50px;">

        <el-form-item label="分配到技能组" prop="assignedSkillGroup">
          <el-select v-model="assignedSkillGroup" multiple style="width:500px">
            <el-option v-for="item in skillGroups" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="分配到个人" prop="assignedUsers">
          <el-tree ref="tree" :data="sysUsers" :default-checked-keys="assignedUsers" show-checkbox node-key="id" highlight-current>
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ data.label }}</span>
            </span>
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAssignedVisible = false">取消</el-button>
        <el-button type="primary" @click="updateAssigned">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listCampaign, createCampaign, updateCampaign, deleteCampaign, allSkillGroup, readAssigned, assignedCampaign } from '@/api/campaign'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'Campaign',
  components: { Pagination },
  data() {
    return {
      assigedOptions: Object.assign({}, defaultAssigedOptions),
      disabled: false,
      uploadPath,
      list: [],
      total: 0,
      listLoading: true,
      sysUsers: [],
      skillGroups: [],
      assignedUsers: [],
      assignedSkillGroup: [],
      assignedCampaignId: 0, // 当前分配任务的id
      listQuery: {
        name: undefined,
        page: 1,
        limit: 20,
        sort: 'id',
        order: 'desc'
      },
      dataForm: {
        id: undefined,
        name: undefined,
        type: 0,
        isCsrOnline: true,
        deleted: false,
        isAutoAssigned: true,
        assignedStart: undefined,
        assignedEnd: undefined,
        isNightRun: false,
        custom_sql: undefined,
        faq: undefined,
        remark: undefined
      },
      dialogFormVisible: false,
      dialogAssignedVisible: false,
      assignedCampaignName: '', // 当前要分配得任务名称
      dialogStatus: '',
      textMap: {
        update: '任务编辑',
        create: '任务创建'
      },
      rules: {
        name: [{ required: true, message: '任务标题不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-JZ-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    filterBoolen(value) {
      if (value == 1) return '是'
      else return '否'
    },
    filterRun(value) {
      if (value == 1) return '每晚一次'
      else return '实时'
    },
    isInputValid(rule, value, callback) {
      if (value == null || value.trim() == '') { return callback(new Error('请输入参数或值')) } else return callback()
    },
    getList() {
      this.listLoading = true
      listCampaign(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        type: 0,
        isCsrOnline: true,
        deleted: false,
        isAutoAssigned: true,
        assignedStart: undefined,
        assignedEnd: undefined,
        isNightRun: false,
        custom_sql: undefined,
        faq: undefined,
        remark: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.disabled = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    assignedChange(e) {
      if (this.dataForm.isAutoAssigned == false) {
        this.dataForm.assignedStart = undefined
        this.dataForm.assignedEnd = undefined
      }
    },
    validData() {
      if (this.dataForm.isAutoAssigned && (this.dataForm.assignedStart == null || this.dataForm.assignedEnd == null)) {
        this.$notify.error({
          title: '失败',
          message: '请选择任务分配的时间段'
        })
        return false
      }
      return true
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.validData() == false) return

          createCampaign(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.disabled = this.dataForm.type == 0

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.validData() == false) return

          updateCampaign(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新任务成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      const status = row.deleted ? '启用' : '停用'

      this.$confirm('确定[' + status + ']此任务？工作期间操作可能会影响坐席任务分配', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCampaign(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '设置' + status + '成功'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      })
    },
    handleAssigned(row) {
      // 获取所有技能组
      if (this.skillGroups.length == 0) {
        allSkillGroup().then(res => {
          this.skillGroups = res.data.data
        })
      }
      this.assignedCampaignName = row.name + ' 分配'
      this.assignedCampaignId = row.id
      // 获取分配信息
      readAssigned({ campaignId: row.id }).then(res => {
        this.assignedUsers = res.data.data.assignedUsers
        this.sysUsers = res.data.data.allUsers
        this.assignedSkillGroup = res.data.data.assignedGroups
      })

      this.dialogAssignedVisible = true
    },
    updateAssigned() { // 任务分配保存
      this.assignedUsers = this.$refs.tree.getCheckedKeys(true)
      if (this.assignedUsers.length == 0 && this.assignedSkillGroup.length == 0) {
        this.$notify.error({
          title: '失败',
          message: '请选择需要至少一个技能组或坐席人员'
        })
        return
      }
      // 保存分配结果
      this.$confirm('确定保存任务[' + this.assignedCampaignName + ']的分配结果？保存后立即生效', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        assignedCampaign({
          assignedSkillGroup: this.assignedSkillGroup,
          assignedUsers: this.assignedUsers,
          campaignId: this.assignedCampaignId
        }).then(res => {
          this.$notify.success({
            title: '成功',
            message: '任务分配成功，如果在设定时间范围，将立即生效'
          })
          this.dialogAssignedVisible = false
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
      })
    }
  }
}

const defaultAssigedOptions = [
  { label: '07:00', value: '07:00' },
  { label: '07:30', value: '07:30' },
  { label: '08:00', value: '08:00' },
  { label: '08:30', value: '08:30' },
  { label: '09:00', value: '09:00' },
  { label: '09:30', value: '09:30' },
  { label: '10:00', value: '10:00' },
  { label: '10:30', value: '10:30' },
  { label: '11:00', value: '11:00' },
  { label: '11:00', value: '11:30' },
  { label: '12:00', value: '12:00' },
  { label: '12:00', value: '12:30' },
  { label: '13:00', value: '13:00' },
  { label: '13:00', value: '13:30' },
  { label: '14:00', value: '14:00' },
  { label: '14:00', value: '14:30' },
  { label: '15:00', value: '15:00' },
  { label: '15:00', value: '15:30' },
  { label: '16:00', value: '16:00' },
  { label: '16:00', value: '16:30' },
  { label: '17:00', value: '17:00' },
  { label: '17:00', value: '17:30' },
  { label: '18:00', value: '18:00' },
  { label: '18:00', value: '18:30' },
  { label: '19:00', value: '19:00' },
  { label: '19:00', value: '19:30' },
  { label: '20:00', value: '20:00' },
  { label: '20:30', value: '20:30' },
  { label: '21:00', value: '21:00' },
  { label: '21:30', value: '21:30' },
  { label: '22:00', value: '22:00' },
  { label: '22:30', value: '22:30' }
]

</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
  .el-table th.gutter{
          display: table-cell!important;
        }

   .tableTitle {
    position: relative;
    margin: 0 auto;
    width: 600px;
    height: 1px;
    background-color: #d4d4d4;
    text-align: center;
    font-size: 16px;
    color: rgba(101, 101, 101, 1);
    margin-bottom: 20px
  }
 .midText {
    position: absolute;
    left: 50%;
    background-color: #ffffff;
    padding: 0 15px;
    transform: translateX(-50%) translateY(-50%);
  }
</style>
