<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入销售公司名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="域名" prop="domain">
        <el-input
          v-model="queryParams.domain"
          placeholder="请输入域名名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <inline-tenant-selector @change="handleQuery" />
      <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"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click="handleAdd"-->
      <!--          v-hasPermi="['platform:companyDomainBind:add']"-->
      <!--        >新增-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['platform:companyDomainBind:edit']"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-connection"
          size="mini"
          :disabled="multiple"
          v-show="!checkDisplay"
          @click="handleDelete"
          v-hasPermi="['platform:companyDomainBind:remove']"
        >解绑
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          v-show="checkDisplay"
          @click="handleExport"
          v-hasPermi="['platform:companyDomainBind:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-paperclip"
          size="mini"
          @click="handleBindingOpen"
        >批量分配销售
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="companyDomainBindList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编码" align="center" prop="id"/>
      <el-table-column label="销售公司编号" align="center" prop="companyId"/>
      <el-table-column label="销售公司名称" align="center" prop="companyName"/>
      <el-table-column label="绑定域名编号" v-if="checkDisplay" align="center" prop="domainId"/>
      <el-table-column label="绑定域名" v-if="checkDisplay" align="center" prop="domain"/>
      <el-table-column label="分配数量" align="center" prop="allocationNum" v-slot="{row}">
        <el-button
          type="text"
          @click="onTableBindNumberClick(row)"
        >{{ row.allocationNum }}
        </el-button>
      </el-table-column>
      <el-table-column label="绑定时间" align="center" prop="createTime" v-slot="{row}">
        <template>
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="!checkDisplay">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-connection"
            v-show="!checkDisplay"
            @click="handleDelete(scope.row)"
            v-hasPermi="['platform:companyDomainBind:remove']"
          >解绑
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--            v-hasPermi="['platform:companyDomainBind:edit']"-->
          <!--          >修改-->
          <!--          </el-button>-->
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['platform:companyDomainBind: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="销售公司ID" prop="companyId">
          <el-input v-model="form.companyId" placeholder="请输入销售公司ID"/>
        </el-form-item>
        <el-form-item label="销售公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入销售公司名称"/>
        </el-form-item>
        <el-form-item label="绑定域名ID" prop="domainId">
          <el-input v-model="form.domainId" placeholder="请输入绑定域名ID"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</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="bindingOpen" width="60%" :before-close="handleClose">
      <el-scrollbar style="height: 692px;">
        <h3>选择分配域名:</h3>
        <el-divider></el-divider>
<!--        <el-form :model="dialog.company.queryParams" ref="companyQueryForm" :inline="true" label-width="68px">-->
<!--          <el-form-item label="公司名称" prop="companyName">-->
<!--            <el-input-->
<!--              v-model="dialog.company.queryParams.companyName"-->
<!--              placeholder="请输入销售公司名称"-->
<!--              clearable-->
<!--              size="small"-->
<!--              @keyup.enter.native="handleQuery"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="域名" prop="domain">-->
<!--            <el-input-->
<!--              v-model="dialog.company.queryParams.domain"-->
<!--              placeholder="请输入域名名称"-->
<!--              clearable-->
<!--              size="small"-->
<!--              @keyup.enter.native="handleQuery"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          <el-form-item>-->
<!--            <inline-tenant-selector @change="handleQuery" />
      <el-button type="primary" icon="el-icon-search" size="mini" @click="companyHandleDialogQuery">搜索-->
<!--            </el-button>-->
<!--            <el-button icon="el-icon-refresh" size="mini" @click="companyResetQuery">重置</el-button>-->
<!--          </el-form-item>-->
<!--        </el-form>-->
        <el-row :span="24">
          <el-col :span="24">
            <span>选择域名：</span>
            <el-select v-model="dialog.company.domainId" filterable placeholder="请选择" @change="domainChange">
              <el-option
                v-for="item in dialog.company.companyList"
                :key="item.id"
                :label="item.domain"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <h3>选择分配销售人员:</h3>
        <el-divider></el-divider>
        <el-form :model="dialog.companyUser.queryParams" ref="dialogQueryForm" :inline="true" v-show="showSearch"
                 label-width="68px"
        >
          <el-form-item label="用户账号" prop="domain">
            <el-input
              v-model="dialog.companyUser.queryParams.userName"
              placeholder="请输入用户账号"
              clearable
              size="small"
              @keyup.enter.native="handleDialogQuery"
            />
          </el-form-item>
          <el-form-item>
            <inline-tenant-selector @change="handleQuery" />
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDialogQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetDialogQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table border v-loading="dialog.companyUser.loading" :data="dialog.companyUser.companyDomainList"
                  @selection-change="handleDialogSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="用户ID" align="center" prop="userId"/>
          <el-table-column label="用户账号" align="center" prop="userName"/>
          <el-table-column label="手机号码" align="center" prop="phonenumber"/>
        </el-table>
        <el-row :span="24">
          <el-col :span="3">
            <span style="margin-top: 100px">已选中绑定域名：{{ dialog.companyUser.ids.length }}条</span>
          </el-col>
          <el-col :span="20">
            <pagination
              v-show="dialog.companyUser.total>0"
              :total="dialog.companyUser.total"
              :page.sync="dialog.companyUser.queryParams.pageNum"
              :limit.sync="dialog.companyUser.queryParams.pageSize"
              @pagination="getDialogList"
            />
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="10" :offset="10">
            <el-button @click="centerDialogVisible">取 消</el-button>
            <el-button type="primary" @click="bindSubmission">确 定</el-button>
          </el-col>
        </el-row>
      </el-scrollbar>
    </el-dialog>

    <!--    企业绑定详情弹窗-->
    <el-dialog title="域名分配 - 人员详情弹窗" :visible.sync="bindingDetailsOpen" width="80%"
               :before-close="handleClose"
    >
      <h3>域名 <b class="domainFont">{{ domainName }}</b> 下分配的人员信息:</h3>
      <el-scrollbar style="height: 692px;">
        <el-divider></el-divider>
        <childCompanyBindUser ref="domainBindUserRef" @bind-value="getList"></childCompanyBindUser>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCompanyDomainBind,
  getCompanyDomainBind,
  delCompanyDomainBind,
  addCompanyDomainBind,
  updateCompanyDomainBind,
  exportCompanyDomainBind,
  domainBatchBinding
} from '@/api/company/companyDomainBind'
import { getCompanyUserListPage } from '@/api/company/companyUser'
import companyBindUser from '@/views/company/companyBindUser/index.vue'

import InlineTenantSelector from "@/components/InlineTenantSelector"

export default {
  name: 'CompanyDomainBind',
  components: {
    InlineTenantSelector, 'childCompanyBindUser': companyBindUser },
  props: {
    isPageCall: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 域名绑定销售公司表格数据
      companyDomainBindList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //检查显示
      checkDisplay: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        companyName: null,
        domainId: null,
        domain: null,
        status: null
      },
      //绑定弹窗显示变量
      bindingOpen: false,
      //弹窗变量
      dialog: {
        companyUser: {
          // 查询参数
          queryParams: {
            pageNum: 1,
            pageSize: 10,
            domain: null,
            status: null,
            userName: null
          },
          // 遮罩层
          loading: true,
          // 域名管路表格数据
          companyDomainList: [],
          // 总条数
          total: 0,
          //选中数组
          ids: []
        },
        platform: {
          queryParams: {
            pageNum: 1,
            pageSize: 10,
            companyName: null,
            companyMobile: null,
            companyAddress: null,
            status: null,
            startTime: null,
            endTime: null,
            money: null,
            times: null,
            voiceApiId: null
          },
          // 遮罩层
          loading: true,
          // 企业数据
          companyList: [],
          // 总条数
          total: 0,
          //选中数组
          ids: [],
          domainId:null,
        }
      },
      bindingDetailsOpen: false,
      //弹窗名称
      domainName: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyId: [
          { required: true, message: '销售公司ID不能为空', trigger: 'blur' }
        ],
        companyName: [
          { required: true, message: '销售公司名称不能为空', trigger: 'blur' }
        ],
        domainId: [
          { required: true, message: '绑定域名ID不能为空', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '创建时间不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.isPageCall) {
      this.getList()
      this.checkDisplay = true
    }
  },
  methods: {
    domainChange(){
      if(this.dialog.company.domainId){
        this.dialog.company.ids.push(this.dialog.company.domainId);
      }
    },
    //判断勾选
    selectable(row, index) {
      return this.displayBoolean;
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {
        })
    },
    formatDate(timestamp) {
      if (!timestamp) return ''

      const date = new Date(timestamp)

      // 自定义日期格式（年-月-日 时:分:秒）
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    /** 查询域名绑定销售公司列表 */
    getList() {
      this.loading = true
      listCompanyDomainBind(this.queryParams).then(response => {
        this.companyDomainBindList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        companyId: null,
        companyName: null,
        domainId: null,
        remark: null,
        createTime: null,
        updateTime: null,
        status: 0,
        createBy: null,
        updateBy: 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
      getCompanyDomainBind(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改域名绑定销售公司'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCompanyDomainBind(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCompanyDomainBind(this.form).then(response => {
              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 delCompanyDomainBind(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
        //触发父组件方法
        this.$emit('bind-value')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有域名绑定销售公司数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        return exportCompanyDomainBind(queryParams)
      }).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => {
      })
    },
    //父级触发接口
    childMethod(domainId) {
      this.queryParams.domainId = domainId
      this.getList()
    },
    /** 弹窗搜索按钮操作 */
    handleDialogQuery() {
      this.dialog.companyUser.queryParams.pageNum = 1
      this.getDialogList()
    },
    //企业重置方法
    companyResetQuery() {
      this.$refs['companyQueryForm'].resetFields()
      this.companyHandleDialogQuery()
    },
    /** 重置按钮操作 */
    resetDialogQuery() {
      this.resetForm('dialogQueryForm')
      this.handleDialogQuery()
    },
    // 多选框选中数据
    handleDialogSelectionChange(selection) {
      this.dialog.companyUser.ids = selection.map(item => item.userId)
    },
    /** 查询域名管路列表 */
    getDialogList() {
      this.dialog.companyUser.loading = true
      getCompanyUserListPage(this.dialog.companyUser.queryParams).then(response => {
        this.dialog.companyUser.companyDomainList = response.rows
        this.dialog.companyUser.total = response.total
        this.dialog.companyUser.loading = false
      })
    },
    companyHandleDialogQuery() {
      this.dialog.company.queryParams.pageNum = 1
      this.getCompanyList()
    },
    // 多选框选中数据
    handleCompanySelectionChange(selection) {
      this.dialog.company.ids = selection.map(item => item.id)
      this.displayBoolean = this.dialog.company.ids.length <= 0;
    },
    /** 查询企业列表 */
    getCompanyList() {
      this.dialog.company.loading = true
      listCompanyDomainBind(this.dialog.company.queryParams).then(response => {
        this.dialog.company.companyList = response.rows
        this.dialog.company.total = response.total
        this.dialog.company.loading = false
      })
    },
    centerDialogVisible() {
      this.bindingOpen = false
      //清空数组
      this.dialog.companyUser.ids = []
      this.dialog.companyUser.queryParams.domain = null
      this.dialog.company.ids = []
      this.dialog.company.queryParams.companyName = null
      this.dialog.company.domainId = null;
    },
    //绑定提交
    bindSubmission() {
      if (this.dialog.companyUser.ids.length === 0) {
        return this.$message.warning({
          message: '绑定失败，请选择分配人员！',
          duration: 2000
        })
      }
      if (this.dialog.company.ids.length === 0) {
        return this.$message.warning({
          message: '绑定失败，请选择分配域名！',
          duration: 2000
        })
      }
      this.domainBatchBinding()
      this.centerDialogVisible()
    },
    //处理绑定
    handleBindingOpen() {
      this.bindingOpen = !this.bindingOpen
      this.dialog.company.queryParams.pageNum=null;
      this.dialog.company.queryParams.pageSize=null;
      this.getDialogList()
      this.getCompanyList()
    },
    //批量绑定
    domainBatchBinding() {
      let param = {
        companyUserIds: this.dialog.companyUser.ids,
        companyIds: this.dialog.company.ids
      }
      domainBatchBinding(param).then(response => {
        this.getList()
        this.msgSuccess(response.msg)
      })
    },
    //表单触发方法
    onTableBindNumberClick(row) {
      this.domainName = row.domain
      this.bindingDetailsOpen = true
      //激活子接口
      this.$nextTick(() => {
        this.$refs.domainBindUserRef.childMethod(row.id)
      })
    }
  }
}
</script>
<style>
.domainFont {
  color: #ff0000;
}
</style>
