<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医生" prop="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入医生姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="升单类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择升单类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="处理状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择处理状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </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>

    <div class="tab-status-filter mb10">
      <el-radio-group v-model="queryParams.status" @change="handleStatusChange" size="small">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button label="0">待处理</el-radio-button>
        <el-radio-button label="1">已完成</el-radio-button>
      </el-radio-group>
    </div>
    <el-table border v-loading="loading" :data="companyUserTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="医生" align="center" prop="doctorName"/>
      <el-table-column label="客户" align="center" prop="name"/>
      <el-table-column label="电话" align="center" prop="phone">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; gap: 8px;">
            <!-- 显示解密后的电话，或原始加密电话，或占位符 -->
            <span class="detail-value">
        {{ scope.row._decryptedPhone !== undefined
              ? (scope.row._decryptedPhone || '—')
              : (scope.row.phone ? '******' : '—') }}
      </span>

            <!-- 放大镜图标按钮 -->
            <el-button
              v-if="scope.row.id"
              type="text"
              icon="el-icon-search"
              size="mini"
              :loading="scope.row._phoneLoading"
              @click="fetchDecryptedPhoneForRow(scope.row)"
              title="点击查看真实号码"
              style="padding: 0; margin-left: 0;"
            ></el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="升单类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="派发时间" align="center" prop="createTime"/>
      <el-table-column label="处理时间" align="center" prop="updateTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleMemberDetails(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-drawer
      :title="show.title"
      :visible.sync="show.open"
      direction="rtl"
      size="75%"
      :before-close="handleCloseDrawer"
      append-to-body
    >
      <overviewUserDetails ref="overviewUserDetails" @close="handleCloseDrawer" />
    </el-drawer>
  </div>
</template>

<script>

import { listCompanyTask,companyGetUserPhone } from "@/api/statistics/sopStatistics";
import overviewUserDetails from '../overviewUserDetails/userDetails.vue';
export default {
  name: "TaskStatsOverview",
  components: {
    overviewUserDetails  // 注册组件
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售处理sop任务表格数据
      companyUserTaskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 处理状态字典
      statusOptions: [],
      // 会员详情抽屉
      show: {
        title: "会员详情",
        open: false,
      },
      // 1:未升单未购 2:未升单已购单 3:升单未购 4:升单已购字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        doctorId: null,
        doctorName: null,
        userId: null,
        name: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},

    };
  },
  created() {
    this.getList();
    this.getDicts("sop_task_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("upgrade_order_type").then(response => {
      this.typeOptions = response.data;
    });
  },
  beforeDestroy() {
    // 关闭抽屉
    this.show.open = false;
  },
  methods: {
    /** 查询销售处理sop任务列表 */
    getList() {
      this.loading = true;
      listCompanyTask(this.queryParams).then(response => {
        // 清理每行的临时解密字段（避免旧数据显示）
        this.companyUserTaskList = (response.rows || []).map(row => {
          const { _decryptedPhone, _phoneLoading, ...cleanRow } = row; // 移除临时字段
          return { ...cleanRow };
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderCode: null,
        doctorId: null,
        userId: null,
        status: null,
        remark: 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
    },

    /** 切换状态Tab */
    handleStatusChange() {
      this.queryParams.pageNum = 1; // 切换时重置页码
      this.getList();
    },
    /** 获取并显示当前行解密后的电话 */
    async fetchDecryptedPhoneForRow(row) {
      if (!row.id || row._phoneLoading) return;

      // 避免重复请求
      this.$set(row, '_phoneLoading', true);

      try {
        const response = await companyGetUserPhone(row.id);
        const phone = response.userPhone || '—';
        this.$set(row, '_decryptedPhone', phone);
      } catch (error) {
        this.$message.error('获取电话失败');
        this.$set(row, '_decryptedPhone', '获取失败');
      } finally {
        this.$set(row, '_phoneLoading', false);
      }
    },
    /** 会员详情按钮操作 */
    handleMemberDetails(row) {
      if (!row.userId) {
        this.$message.warning("该客户未绑定会员");
        return;
      }

      this.show.title = `会员详情 - ${row.name || '未知客户'}`;
      this.show.open = true;

      // 确保DOM更新后再调用子组件方法
      this.$nextTick(() => {
        if (this.$refs.overviewUserDetails) {
          this.$refs.overviewUserDetails.getDetails(row.userId, row);
        }
      });
    },

    /** 关闭会员详情抽屉 */
    handleCloseDrawer() {
      this.show.open = false;
      // 重置子组件状态
      if (this.$refs.overviewUserDetails && this.$refs.overviewUserDetails.reset) {
        this.$refs.overviewUserDetails.reset();
      }
    },
  }
};
</script>

<style scoped>
.mb10 {
  margin-bottom: 10px;
}

.tab-status-filter {
  margin-bottom: 10px;
}

.detail-value {
  font-weight: 500;
  color: #606266;
}
</style>
