<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主体名称" prop="corpId">
        <el-select v-model="queryParams.corpId" placeholder="请选择主体名称" clearable filterable>
          <el-option
            v-for="item in corpOptions"
            :key="item.CorpId"
            :label="item.corpName"
            :value="item.CorpId">
          </el-option>
        </el-select>
      </el-form-item>
      <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="companyUserName">
        <el-input
          v-model="queryParams.companyUserName"
          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 >
          <el-option :value="0" label="全部"/>
          <el-option
            v-for="item in auditStatusOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </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-table v-loading="loading" :data="list" border>
      <el-table-column label="ID" align="center" prop="id" width="80px"/>
      <el-table-column label="接替公司名称" align="center" prop="companyName" />
      <el-table-column label="主体名称" align="center">
        <template slot-scope="scope">
          {{ getCorpNameByCorpId(scope.row.corpId) || scope.row.corpName }}
        </template>
      </el-table-column>
      <el-table-column label="接替销售名称" align="center" prop="companyUserName" />
      <el-table-column label="接替企微用户名称" align="center" prop="qwUserName" />
      <el-table-column label="审核状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="auditStatusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" align="center" prop="createTime" />
      <el-table-column label="审核时间" align="center" prop="auditTime" />
      <el-table-column label="被拒原因" align="center" prop="reason" />
      <el-table-column label="提交人" align="center" prop="createBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleAudit(scope.row)"
            v-if="scope.row.status === 1"
            v-hasPermi="['qw:externalContactTransferCompanyAudit:audit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['qw:externalContactTransferCompanyAudit:detail']"
          >详情</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="审核" :visible.sync="dialogAuditVisible" width="800px" append-to-body>
      <el-form :model="from" ref="auditForm" :rules="rules" label-width="100px">
        <el-form-item label="审核结果" prop="type">
          <el-radio-group v-model="from.type">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="from.type === '2'" label="拒绝原因" prop="reason">
          <el-input type="textarea" :rows="2" v-model="from.reason" placeholder="请输入拒绝原因" clearable size="small" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"
                   @click="submitForm"
                   :disabled="submitLoading"
                   :loading="submitLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer title="详情" size="75%" :visible.sync="dialogViewVisible" append-to-body>
      <el-table v-loading="detailLoading" :data="userList" border>
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="客户名称" align="center" prop="externalUserName" />
        <el-table-column label="原公司名称" align="center" prop="companyName" />
        <el-table-column label="原销售名称" align="center" prop="companyUserName" />
        <el-table-column label="原企微用户名称" align="center" prop="qwUserName" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="接替状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="replaceStatusOptions" :value="scope.row.status"/>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="detailTotal>0"
        :total="detailTotal"
        :page.sync="detailQueryParams.pageNum"
        :limit.sync="detailQueryParams.pageSize"
        @pagination="handleDetailPagination"
      />
    </el-drawer>
  </div>
</template>

<script>
import { audit, detail, listExternalContactTransferAudit } from '@/api/qw/externalContactTransferAudit'
import { getMyQwCompanyList } from '@/api/qw/user'

export default {
  name: "externalContactTransferAudit",
  data() {
    return {
      loading: false,
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        corpId: null,
        companyUserName: null,
        status: 0,
      },
      total: 0,
      list: [],
      auditStatusOptions: [],
      replaceStatusOptions: [],
      dialogAuditVisible: false,
      dialogViewVisible: false,
      detailLoading: false,
      userList: [],
      detailTotal: 0,
      detailQueryParams: {
        pageNum: 1,
        pageSize: 10,
        auditId: null
      },
      from: {
        id: null,
        type: null,
        reason: null
      },
      rules: {
        type: [
          { required: true, message: "请选择审核结果", trigger: "blur" }
        ]
      },
      submitLoading: false,
      corpOptions: [],
    }
  },
  created() {
    this.getDicts("sys_qw_transfer_audit_status").then((response) => {
      this.auditStatusOptions = response.data;
    });
    this.getDicts("sys_qw_transfer_status").then((response) => {
      this.replaceStatusOptions = response.data;
    });
    this.getCorpOptions()
    this.handleQuery()
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        corpId: null,
        companyUserName: null,
        status: 0,
      };
      this.$nextTick(() => {
        this.resetForm("queryForm");
        this.handleQuery();
      });
    },
    getCorpOptions() {
      // 调用接口获取主体名称下拉选项
      getMyQwCompanyList().then(response => {
        if (response.data && Array.isArray(response.data)) {
          // 确保CorpId和corpName字段正确处理
          this.corpOptions = response.data.map(item => {
            return {
              CorpId: item.dictValue ? item.dictValue.toString() : '',  // 使用corpId而不是CorpId
              corpName: item.dictLabel || ''
            };
          });
        } else {
          this.corpOptions = [];
        }
      }).catch(error => {
        console.error('获取主体名称列表失败:', error);
        this.corpOptions = [];
      });
    },
    // 添加一个方法来根据CorpId获取corpName
    getCorpNameByCorpId(corpId) {
      if (!corpId || !this.corpOptions || this.corpOptions.length === 0) {
        return '';
      }

      // 查找匹配的corpName
      const corp = this.corpOptions.find(item => item.CorpId === (corpId ? corpId.toString() : ''));
      return corp ? corp.corpName : '';
    },
    getList() {
      this.loading = true
      const params = {
        ...this.queryParams,
        status: this.queryParams.status === 0 ? null : this.queryParams.status
      }

      // 如果选择了主体名称，则将其作为corpId传递，否则删除该参数
      if (this.queryParams.corpId) {
        params.corpId = this.queryParams.corpId;
      } else {
        delete params.corpId;
      }

      listExternalContactTransferAudit(params).then(response => {
        this.list = response.rows.map(item => {
          return {
            ...item,
            corpId: item.corpId ? item.corpId.toString() : item.corpId, // 确保corpId也是字符串类型
            createTime: item.createTime ? item.createTime.replace("T", " ") : null,
            auditTime: item.auditTime ? item.auditTime.replace("T", " ") : null,
          }
        })
        this.total = response.total
        this.loading = false
      })
    },
    reset() {
      this.from = {
        id: null,
        type: null,
        reason: null
      }
      this.resetForm("auditForm")
    },
    handleAudit(row) {
      this.reset()
      this.from.id = row.id
      this.submitLoading = false
      this.dialogAuditVisible = true
    },
    handleView(row) {
      this.detailLoading = true
      this.detailQueryParams.auditId = row.id
      this.detailQueryParams.pageNum = 1
      this.getDetailList()
      this.dialogViewVisible = true
    },
    handleDetailPagination({ page, limit }) {
      this.detailQueryParams.pageNum = page
      this.detailQueryParams.pageSize = limit
      this.getDetailList()
    },
    getDetailList() {
      this.detailLoading = true
      // 确保传递正确的分页参数
      const params = {
        pageNum: this.detailQueryParams.pageNum,
        pageSize: this.detailQueryParams.pageSize
      };

      detail(this.detailQueryParams.auditId, params).then(response => {
        this.userList = response.rows
        this.detailTotal = response.total
        this.detailLoading = false
      }).catch(() => {
        this.detailLoading = false
      })
    },
    submitForm() {
      this.$refs["auditForm"].validate(valid => {
        if (valid) {
          if (this.submitLoading) {
             return
          }
          this.submitLoading = true
          const params = {
            auditId: this.from.id,
            type: this.from.type,
            reason: this.from.reason
          }
          audit(params).then(() => {
            this.$message.success("操作成功, 请在详情查看转接结果");
            this.dialogAuditVisible = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.dialogAuditVisible = false
      this.reset()
    },
  }
}
</script>
