<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <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 label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="item in statusOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          >
          </el-option>
        </el-select>
      </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:companyDomain: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:companyDomain:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['platform:companyDomain:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['platform:companyDomain:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-paperclip"
          size="mini"
          @click="handleBindingOpen"
          v-hasPermi="['platform:companyDomain:edit']"
        >批量绑定
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="companyDomainList" @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="domain"/>
      <el-table-column label="域名绑定企业数量" align="center" prop="bindNum" v-slot="{row}">
        <el-button
          type="text"
          @click="onTableBindNumberClick(row)"
        >{{ row.bindNum }}
        </el-button>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <el-tag prop="status" v-for="(item, index) in statusOptions" :key="item.dictValue"
                  :type="scope.row.status==1?'success':'danger'"
                  v-if="scope.row.status==item.dictValue"
          >{{ item.dictLabel }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 模板同上 -->
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template v-slot="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['platform:companyDomain:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['platform:companyDomain: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" center append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="域名" prop="domain">
          <el-input v-model="form.domain" placeholder="请输入域名"/>
        </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
              v-for="item in statusOptions"
              :key="item.dictValue"
              :label="item.dictValue"
            >{{ item.dictLabel }}
            </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.domain.queryParams" ref="dialogQueryForm" :inline="true" v-show="showSearch"
                 label-width="68px"
        >
          <el-form-item label="域名" prop="domain">
            <el-input
              v-model="dialog.domain.queryParams.domain"
              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.domain.loading" :data="dialog.domain.companyDomainList"
                  @selection-change="handleDialogSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="编号" align="center" prop="id"/>
          <el-table-column label="域名" align="center" prop="domain"/>
          <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" prop="remark"/>
        </el-table>
        <el-row :span="24">
          <el-col :span="3">
            <span style="margin-top: 100px">已选中绑定域名：{{ dialog.domain.ids.length }}条</span>
          </el-col>
          <el-col :span="20">
            <pagination
              v-show="dialog.domain.total>0"
              :total="dialog.domain.total"
              :page.sync="dialog.domain.queryParams.pageNum"
              :limit.sync="dialog.domain.queryParams.pageSize"
              @pagination="getDialogList"
            />
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <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
              style="width: 220px"
              v-model="dialog.company.queryParams.companyName"
              placeholder="请输入企业名称"
              clearable
              size="small"
              @keyup.enter.native="companyResetQuery"
            />
          </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-table border v-loading="dialog.company.loading" :data="dialog.company.companyList"
                  @selection-change="handleCompanySelectionChange"
        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="公司名称" align="center" prop="companyName"/>
          <el-table-column label="类型" align="center" prop="companyType">
            <template slot-scope="scope">
              <el-tag prop="companyType" v-for="(item, index) in typeOptions" :key="item.dictLabel"
                      v-if="scope.row.companyType==item.dictValue"
              >{{ item.dictLabel }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime">
          </el-table-column>
        </el-table>
        <el-row :span="24">
          <el-col :span="3">
            <span style="margin-top: 100px">已选中绑定公司：{{ dialog.company.ids.length }}条</span>
          </el-col>
          <el-col :span="20">
            <pagination
              v-show="dialog.company.total>0"
              :total="dialog.company.total"
              :page.sync="dialog.company.queryParams.pageNum"
              :limit.sync="dialog.company.queryParams.pageSize"
              @pagination="getCompanyList()"
            />
          </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="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
          </div>
          <div class="el-upload__tip" slot="tip">
            只能上传.xlsx或.xls文件，且不超过5MB
          </div>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="exportTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
    </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>
        <childDomainBind ref="domainBindRef" @bind-value="getList()" :isPageCall="false"></childDomainBind>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCompanyDomain,
  getCompanyDomain,
  delCompanyDomain,
  addCompanyDomain,
  updateCompanyDomain,
  exportCompanyDomain,
  domainBatchBinding,
  exportTemplate
} from '@/api/company/companyDomain'
import { listCompany } from '@/api/company/company'
import { getToken } from '@/utils/auth'
import domainBind from '@/views/company/companyDomainBind/index.vue'

import InlineTenantSelector from "@/components/InlineTenantSelector"

export default {
  name: 'CompanyDomain',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 域名管路表格数据
      companyDomainList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      statusOptions: [],
      //详情弹窗变量
      bindingDetailsOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        domain: null,
        status: null
      },
      //上传
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/company/companyDomain/importDomainData'
      },
      //绑定弹窗显示变量
      bindingOpen: false,
      // 表单参数
      form: {
        status: ''
      },
      typeOptions: [],
      // 表单校验
      rules: {
        domain: [
          { required: true, message: '域名不能为空', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '创建时间不能为空', trigger: 'blur' }
        ]
      },
      //弹窗变量
      dialog: {
        domain: {
          // 查询参数
          queryParams: {
            pageNum: 1,
            pageSize: 10,
            domain: null,
            status: 1
          },
          // 遮罩层
          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: []
        }
      },
      //弹窗名称
      domainName: null,
      //临时存域名ids
      domainTemporaryIds: [],
      //临时存公司ids
      companyTemporaryIds: []
    }
  },
  components: {
    InlineTenantSelector,
    'childDomainBind': domainBind
  },
  created() {
    this.getList()

    //字典状态查询
    this.getDicts('sys_company_status').then((response) => {
      this.statusOptions = response.data
    })

    //企业类型
    this.getDicts('sys_company_type').then((response) => {
      this.typeOptions = response.data
    })
  },
  methods: {
    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
      listCompanyDomain(this.queryParams).then(response => {
        this.companyDomainList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询域名管路列表 */
    getDialogList() {
      this.dialog.domain.loading = true
      listCompanyDomain(this.dialog.domain.queryParams).then(response => {
        this.dialog.domain.companyDomainList = response.rows
        this.dialog.domain.total = response.total
        this.dialog.domain.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        domain: null,
        remark: null,
        createTime: null,
        updateTime: null,
        status: 0,
        createBy: null,
        updateBy: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 弹窗搜索按钮操作 */
    handleDialogQuery() {
      this.dialog.domain.queryParams.pageNum = 1
      this.getDialogList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 重置按钮操作 */
    resetDialogQuery() {
      this.resetForm('dialogQueryForm')
      this.handleDialogQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 多选框选中数据
    handleDialogSelectionChange(selection) {
      this.dialog.domain.ids = selection.map(item => item.id)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加域名管路'
      this.form.status = '1'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCompanyDomain(id).then(response => {
        this.form = response.data
        this.form.status = response.data.status === 1 ? '1' : '0'
        this.open = true
        this.title = '修改域名管路'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCompanyDomain(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCompanyDomain(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 delCompanyDomain(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有域名管路数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        return exportCompanyDomain(queryParams)
      }).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => {
      })
    },
    //处理绑定
    handleBindingOpen() {
      this.bindingOpen = !this.bindingOpen
      this.getDialogList()
      this.getCompanyList()
    },
    //企业重置方法
    companyResetQuery() {
      this.$refs['companyQueryForm'].resetFields()
      this.companyHandleDialogQuery()
    },
    companyHandleDialogQuery() {
      this.dialog.company.queryParams.pageNum = 1
      this.getCompanyList()
    },
    /** 查询企业列表 */
    getCompanyList() {
      this.dialog.company.loading = true
      listCompany(this.dialog.company.queryParams).then(response => {
        this.dialog.company.companyList = response.rows
        this.dialog.company.total = response.total
        this.dialog.company.loading = false
      })
    },
    // 多选框选中数据
    handleCompanySelectionChange(selection) {
      this.dialog.company.ids = selection.map(item => item.companyId)
    },
    //绑定提交
    bindSubmission() {
      if (this.dialog.domain.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()
    },
    centerDialogVisible() {
      this.bindingOpen = false
      //清空数组
      this.dialog.domain.ids = []
      this.dialog.domain.queryParams.domain = null
      this.dialog.company.ids = []
      this.dialog.company.queryParams.companyName = null
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {
        })
    },
    //批量绑定
    domainBatchBinding() {
      let param = {
        domainIds: this.dialog.domain.ids,
        companyIds: this.dialog.company.ids
      }
      domainBatchBinding(param).then(response => {
        this.getList()
        this.msgSuccess(response.msg)
      })
    },
    //导入按钮操作
    handleImport() {
      this.upload.title = '导入'
      this.upload.open = true
    },
    // 文件上传前校验
    beforeUpload(file) {
      // 校验文件类型
      const isValidType = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-excel'].includes(file.type)

      // 校验文件扩展名
      const fileExtension = file.name.split('.').pop().toLowerCase()
      const isValidExtension = ['xlsx', 'xls'].includes(fileExtension)

      // 校验文件大小 (5MB = 5 * 1024 * 1024 字节)
      const isValidSize = file.size <= 5 * 1024 * 1024

      if (!isValidType || !isValidExtension) {
        this.$message.error('请上传Excel文件 (.xlsx 或 .xls)')
        return false
      }

      if (!isValidSize) {
        this.$message.error('文件大小不能超过5MB')
        return false
      }

      return true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 上传失败处理
    handleUploadError(error, file, fileList) {
      this.upload.isUploading = false
      this.upload.message = '上传失败，请重试'
      this.upload.type = 'error'

      // 处理上传失败后的逻辑
      console.error('上传失败:', error)
    },
    //下载模板
    exportTemplate() {
      exportTemplate().then(response => {
        this.download(response.msg)
      })
    },
    //表单触发方法
    onTableBindNumberClick(row) {
      this.domainName = row.domain
      this.bindingDetailsOpen = true
      //激活子接口
      this.$nextTick(() => {
        this.$refs.domainBindRef.childMethod(row.id)
      })
    }
  }
}
</script>
<style scoped>
::v-deep .el-radio {
  margin-right: 24px !important; /* 使用 !important 提高优先级 */
}

.domainFont {
  color: #ff0000;
}
</style>
