<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="外呼任务" prop="roboticId">
        <el-select v-model="queryParams.roboticId" filterable clearable placeholder="请选择任务">
          <el-option v-for="item in roboticList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="分机号" prop="answeredExtNum">
        <el-input
          v-model="queryParams.answeredExtNum"
          placeholder="请输入分机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" border>
      <el-table-column label="ID" align="center" prop="logId" width="80"/>
      <el-table-column label="任务名称" align="center" prop="roboticName" show-overflow-tooltip/>
      <el-table-column label="客户号码" align="center" prop="callerNum" width="130">
        <template slot-scope="scope">
          <span>{{ desensitizePhone(scope.row.callerNum) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接听分机" align="center" prop="answeredExtNum" width="100"/>
      <el-table-column label="销售姓名" align="center" prop="companyUserName" width="100"/>
      <el-table-column label="AI通话时长(秒)" align="center" prop="callTime" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.callTime || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="人工接听时长(秒)" align="center" prop="manualAnsweredTimeLen" width="130">
        <template slot-scope="scope">
          <span>{{ msToSeconds(scope.row.manualAnsweredTimeLen) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="呼入时间" align="center" prop="callCreateTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.callCreateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="人工接听时间" align="center" prop="manualAnsweredTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.manualAnsweredTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" align="center" prop="handleFlag" width="90">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.handleFlag === 1" type="success">已处理</el-tag>
          <el-tag v-else type="danger">未处理</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.handleFlag !== 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleProcess(scope.row)"
            v-hasPermi="['company:handleManualAnswered:handle']"
          >处理数据</el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</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="processDialogVisible" width="600px" append-to-body>
      <el-form ref="processForm" :model="processForm" label-width="110px" v-loading="processLoading">
        <el-form-item label="客户名称">
          <span>{{ processForm.customerName }}</span>
        </el-form-item>
        <el-form-item label="客户号码">
          <span>{{ desensitizePhone(processForm.mobile) }}</span>
        </el-form-item>
        <el-form-item label="有效客户" prop="effectiveCustomer">
          <el-radio-group v-model="processForm.effectiveCustomer">
            <el-radio :label="1">有效</el-radio>
            <el-radio :label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="AI外呼备注" prop="aiCallRemark">
          <el-input
            v-model="processForm.aiCallRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入AI外呼备注"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="processDialogVisible = false">取 消</el-button>
        <el-tooltip placement="top">
          <div slot="content">仅将此条外呼记录标记为已处理，<br/>不会修改客户的任何信息（有效客户、备注等）</div>
          <el-button type="warning" @click="handleConfirmInfo" :loading="confirmLoading">确认信息</el-button>
        </el-tooltip>
        <el-button type="primary" @click="submitProcess" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看弹窗（已处理时使用，只读展示） -->
    <el-dialog title="查看处理结果" :visible.sync="viewDialogVisible" width="600px" append-to-body>
      <el-form :model="viewForm" label-width="110px" v-loading="viewLoading">
        <el-form-item label="客户名称">
          <span>{{ viewForm.customerName }}</span>
        </el-form-item>
        <el-form-item label="客户号码">
          <span>{{ desensitizePhone(viewForm.mobile) }}</span>
        </el-form-item>
        <el-form-item label="有效客户">
          <el-tag v-if="viewForm.effectiveCustomer === 1" type="success">有效</el-tag>
          <el-tag v-else type="info">无效</el-tag>
        </el-form-item>
        <el-form-item label="AI外呼备注">
          <span>{{ viewForm.aiCallRemark || '无' }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listManualAnswered, getCrmCustomerByLogId, confirmManualAnswered, submitManualAnswered } from "@/api/company/callphone";
import { listAll as roboticListAll } from "@/api/company/companyVoiceRobotic";

export default {
  name: "HandleManualAnswered",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 列表数据
      list: [],
      // 任务下拉列表
      roboticList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roboticId: null,
        answeredExtNum: null
      },
      // 处理数据弹窗
      processDialogVisible: false,
      processLoading: false,
      submitLoading: false,
      confirmLoading: false,
      processForm: {},
      currentLogId: null,
      // 查看弹窗
      viewDialogVisible: false,
      viewLoading: false,
      viewForm: {}
    };
  },
  created() {
    this.getList();
    this.getRoboticList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listManualAnswered(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取任务下拉列表 */
    getRoboticList() {
      roboticListAll().then(response => {
        this.roboticList = response.data || [];
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 处理数据按钮 */
    handleProcess(row) {
      this.currentLogId = row.logId;
      this.processForm = {};
      this.processDialogVisible = true;
      this.processLoading = true;
      getCrmCustomerByLogId(row.logId).then(response => {
        if (response.code === 200 && response.data) {
          this.processForm = response.data;
        } else {
          this.processForm = {};
        }
        this.processLoading = false;
      }).catch(() => {
        this.processForm = {};
        this.processLoading = false;
      });
    },
    /** 查看处理结果（已处理数据，只读展示） */
    handleView(row) {
      this.viewForm = {};
      this.viewDialogVisible = true;
      this.viewLoading = true;
      getCrmCustomerByLogId(row.logId).then(response => {
        if (response.code === 200 && response.data) {
          this.viewForm = response.data;
        } else {
          this.viewForm = {};
        }
        this.viewLoading = false;
      }).catch(() => {
        this.viewForm = {};
        this.viewLoading = false;
      });
    },
    /** 确认信息（仅标记外呼记录为已处理，不更新客户信息） */
    handleConfirmInfo() {
      this.confirmLoading = true;
      confirmManualAnswered({ logId: this.currentLogId }).then(response => {
        if (response.code === 200) {
          this.$message.success('已确认处理');
          this.processDialogVisible = false;
          this.getList();
        }
        this.confirmLoading = false;
      }).catch(() => {
        this.confirmLoading = false;
      });
    },
    /** 提交处理（标记外呼记录为已处理 + 更新CRM客户信息） */
    submitProcess() {
      const submitData = {
        customerId: this.processForm.customerId,
        effectiveCustomer: this.processForm.effectiveCustomer,
        aiCallRemark: this.processForm.aiCallRemark,
        effectiveRecordPath: this.processForm.effectiveRecordPath,
        lastEffectiveCallphoneLogId: this.currentLogId
      };
      this.submitLoading = true;
      submitManualAnswered(submitData).then(response => {
        if (response.code === 200) {
          this.$message.success('处理成功');
          this.processDialogVisible = false;
          this.getList();
        }
        this.submitLoading = false;
      }).catch(() => {
        this.submitLoading = false;
      });
    },
    /** 手机号脱敏：前3位 + **** + 后4位 */
    desensitizePhone(phone) {
      if (!phone) return '';
      const str = String(phone);
      if (str.length >= 7) {
        return str.substring(0, 3) + '****' + str.substring(str.length - 4);
      }
      return str;
    },
    /** 毫秒转秒（向上取整） */
    msToSeconds(ms) {
      if (!ms || ms <= 0) return 0;
      return Math.ceil(ms / 1000);
    }
  }
};
</script>
