<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="AppId" prop="appId">
        <el-input
          v-model="queryParams.appId"
          placeholder="请输入AppId"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="绑定状态" prop="bindStatus">
        <el-select v-model="queryParams.bindStatus" placeholder="请选择" clearable size="small">
          <el-option label="未绑定" :value="0" />
          <el-option label="已绑定" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售名称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入销售名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属公司" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          placeholder="请选择公司"
          clearable
          filterable
          size="small"
          style="width: 200px"
        >
          <el-option
            v-for="item in companyOptions"
            :key="item.companyId"
            :label="item.companyName"
            :value="item.companyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" 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="['qw:feishuAccount: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="['qw:feishuAccount:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="AppId" align="center" prop="appId" min-width="160" show-overflow-tooltip />
      <el-table-column label="AppSecret" align="center" prop="appSecret" min-width="180" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            v-hasPermi="['qw:feishuAccount:edit']"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="绑定销售" align="center" min-width="220">
        <template slot-scope="scope">
          <span v-if="scope.row.companyUserId">
            {{ scope.row.nickName || '-' }}（{{ scope.row.companyUserId }}）
            <span v-if="scope.row.companyName" style="color:#909399">{{ scope.row.companyName }}</span>
          </span>
          <el-tag v-else type="info" size="mini">未绑定</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="错误信息" align="center" prop="errorMsg" min-width="140" show-overflow-tooltip />
      <el-table-column label="所属分组" align="center" prop="deptName" width="120" />
      <el-table-column label="已使用次数" align="center" prop="numberUse" width="110">
        <template slot-scope="scope">
          {{ scope.row.numberUse != null ? scope.row.numberUse : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="170">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qw:feishuAccount:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleAssign(scope.row)"
            v-hasPermi="['qw:feishuAccount:assign']"
          >分配销售</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qw:feishuAccount: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-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="AppId" prop="appId">
          <el-input v-model="form.appId" placeholder="请输入飞书AppId" />
        </el-form-item>
        <el-form-item label="AppSecret" prop="appSecret">
          <el-input v-model="form.appSecret" placeholder="请输入飞书AppSecret" show-password />
        </el-form-item>
        <el-form-item label="所属公司" prop="companyId">
          <el-select
            v-model="form.companyId"
            placeholder="选填，绑定销售时先选公司"
            filterable
            clearable
            style="width: 100%"
            @change="handleFormCompanyChange"
          >
            <el-option
              v-for="item in companyOptions"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定销售" prop="companyUserId">
          <el-select
            v-model="form.companyUserId"
            placeholder="选填，请先选择公司"
            filterable
            clearable
            style="width: 100%"
            :disabled="!form.companyId"
          >
            <el-option
              v-for="item in formSalesOptions"
              :key="item.userId"
              :label="(item.nickName || item.userName) + '（userId: ' + item.userId + '）'"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="已使用次数" prop="numberUse">
          <el-input-number v-model="form.numberUse" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </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>

    <!-- 分配销售 -->
    <el-dialog title="分配销售" :visible.sync="assignOpen" width="520px" append-to-body>
      <el-form ref="assignForm" :model="assignForm" :rules="assignRules" label-width="100px">
        <el-form-item label="AppId">
          <el-input :value="assignForm.appId" disabled />
        </el-form-item>
        <el-form-item label="已使用次数">
          <el-input :value="assignForm.numberUse != null ? assignForm.numberUse : 0" disabled />
        </el-form-item>
        <el-form-item label="所属公司" prop="companyId">
          <el-select
            v-model="assignForm.companyId"
            placeholder="请选择公司"
            filterable
            clearable
            style="width: 100%"
            @change="handleAssignCompanyChange"
          >
            <el-option
              v-for="item in companyOptions"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售账号" prop="companyUserId">
          <el-select
            v-model="assignForm.companyUserId"
            placeholder="请先选择公司再选销售"
            filterable
            clearable
            style="width: 100%"
            :disabled="!assignForm.companyId"
            @change="handleAssignUserChange"
          >
            <el-option
              v-for="item in salesOptions"
              :key="item.userId"
              :label="(item.nickName || item.userName) + '（' + item.userId + '）'"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-alert
          title="清空公司/销售并提交即可解绑"
          type="info"
          :closable="false"
          show-icon
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAssign">确 定</el-button>
        <el-button @click="assignOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFeishuAccount,
  getFeishuAccount,
  delFeishuAccount,
  addFeishuAccount,
  updateFeishuAccount,
  changeFeishuAccountStatus,
  assignFeishuAccountSales
} from '@/api/qw/feishuAccount'
import { getCompanyList } from '@/api/company/company'
import { listCompanyUser } from '@/api/company/companyUser'

export default {
  name: 'FeishuAccount',
  data() {
    return {
      loading: true,
      ids: [],
      multiple: true,
      showSearch: true,
      total: 0,
      accountList: [],
      companyOptions: [],
      salesOptions: [],
      formSalesOptions: [],
      title: '',
      open: false,
      assignOpen: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        appId: null,
        phone: null,
        status: null,
        nickName: null,
        companyId: null,
        bindStatus: null
      },
      form: {
        id: null,
        appId: null,
        appSecret: null,
        status: 1,
        errorMsg: null,
        phone: null,
        numberUse: null,
        companyId: null,
        companyUserId: null
      },
      rules: {
        appId: [{ required: true, message: 'AppId不能为空', trigger: 'blur' }],
        appSecret: [{ required: true, message: 'AppSecret不能为空', trigger: 'blur' }]
      },
      assignForm: {
        id: null,
        appId: null,
        numberUse: null,
        companyId: null,
        companyUserId: null,
        phone: null
      },
      assignRules: {}
    }
  },
  created() {
    this.getList()
    this.loadCompanyOptions()
  },
  methods: {
    getList() {
      this.loading = true
      listFeishuAccount(this.queryParams).then(response => {
        this.accountList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    loadCompanyOptions() {
      getCompanyList().then(response => {
        this.companyOptions = response.data || []
      }).catch(() => {
        this.companyOptions = []
      })
    },
    loadSalesOptions(companyId) {
      this.salesOptions = []
      if (!companyId) {
        return
      }
      listCompanyUser({
        pageNum: 1,
        pageSize: 500,
        companyId
      }).then(response => {
        this.salesOptions = response.rows || []
      })
    },
    loadFormSalesOptions(companyId) {
      this.formSalesOptions = []
      if (!companyId) {
        return
      }
      listCompanyUser({
        pageNum: 1,
        pageSize: 500,
        companyId
      }).then(response => {
        this.formSalesOptions = response.rows || []
      })
    },
    handleFormCompanyChange(companyId) {
      this.form.companyUserId = null
      this.loadFormSalesOptions(companyId)
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.nickName = null
      this.queryParams.companyId = null
      this.queryParams.bindStatus = null
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    reset() {
      this.form = {
        id: null,
        appId: null,
        appSecret: null,
        status: 1,
        errorMsg: null,
        phone: null,
        numberUse: null,
        companyId: null,
        companyUserId: null
      }
      this.formSalesOptions = []
      this.resetForm('form')
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增飞书应用账号'
    },
    handleUpdate(row) {
      this.reset()
      getFeishuAccount(row.id).then(response => {
        this.form = {
          ...response.data,
          companyId: response.data.companyId || null,
          companyUserId: response.data.companyUserId || null
        }
        if (this.form.companyId) {
          this.loadFormSalesOptions(this.form.companyId)
        }
        this.open = true
        this.title = '修改飞书应用账号'
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        if ((this.form.companyId && !this.form.companyUserId) || (!this.form.companyId && this.form.companyUserId)) {
          return this.$message.error('公司和销售需同时选择，或同时留空')
        }
        const payload = {
          ...this.form,
          companyId: this.form.companyId || null,
          companyUserId: this.form.companyUserId || null
        }
        if (this.form.id != null) {
          updateFeishuAccount(payload).then(() => {
            this.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
        } else {
          addFeishuAccount(payload).then(() => {
            this.msgSuccess('新增成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delFeishuAccount(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleStatusChange(row) {
      const newStatus = row.status
      const oldStatus = newStatus === 1 ? 0 : 1
      const text = newStatus === 1 ? '启用' : '禁用'
      this.$confirm('确认要' + text + '该账号吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return changeFeishuAccountStatus({
          id: row.id,
          status: newStatus,
          errorMsg: newStatus === 1 ? '' : row.errorMsg
        })
      }).then(() => {
        this.msgSuccess('状态修改成功')
        this.getList()
      }).catch(() => {
        row.status = oldStatus
      })
    },
    handleAssign(row) {
      this.assignForm = {
        id: row.id,
        appId: row.appId,
        numberUse: row.numberUse != null ? row.numberUse : 0,
        companyId: row.companyId || null,
        companyUserId: row.companyUserId || null,
        phone: null
      }
      this.salesOptions = []
      if (this.assignForm.companyId) {
        this.loadSalesOptions(this.assignForm.companyId)
      }
      this.assignOpen = true
    },
    handleAssignCompanyChange(companyId) {
      this.assignForm.companyUserId = null
      this.assignForm.phone = null
      this.loadSalesOptions(companyId)
    },
    handleAssignUserChange() {
      // 不再回填电话号码
      this.assignForm.phone = null
    },
    submitAssign() {
      const payload = {
        id: this.assignForm.id,
        companyId: this.assignForm.companyId || null,
        companyUserId: this.assignForm.companyUserId || null,
        phone: null
      }
      if ((payload.companyId && !payload.companyUserId) || (!payload.companyId && payload.companyUserId)) {
        return this.$message.error('公司和销售需同时选择，或同时清空以解绑')
      }
      assignFeishuAccountSales(payload).then(() => {
        this.msgSuccess('分配成功')
        this.assignOpen = false
        this.getList()
      })
    }
  }
}
</script>
