<template>
  <div class="app-container objection-container">
    <DragResizePanel :initialSize="280" :minSize="280" :maxSize="600">
      <template #panelA>
        <div class="left-panel">
          <div class="panel-header">
            <div class="header-title">
              <i class="el-icon-edit-outline"></i>
              <span>待处理意见</span>
              <el-button size="mini" type="text" icon="el-icon-refresh" @click="getList" style="margin-left:4px;"
                title="刷新列表"></el-button>
            </div>
            <el-select v-model="queryParams.taskStatus" placeholder="任务状态" clearable size="mini" @change="handleQuery"
              class="header-filter">
              <el-option label="待填写" :value="0" />
              <el-option label="已完成" :value="1" />
            </el-select>
          </div>

          <div class="search-row">
            <el-input v-model="queryParams.complaintNo" placeholder="搜索售后编号..." clearable prefix-icon="el-icon-search"
              size="small" @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </div>

          <div v-loading="loading" class="list-body">
            <div v-for="item in taskList" :key="item.taskId" class="list-item"
              :class="{ active: currentTask && currentTask.taskId === item.taskId }" @click="handleRowClick(item)">
              <div class="item-main">
                <span class="item-title">{{ (item.acceptInfo || {}).complaintNo || '' }}</span>
                <span class="item-sub">{{ parseTime((item.acceptInfo || {}).complaintDate, '{y}-{m}-{d}') }}</span>
              </div>
              <div class="item-meta">
                <el-tag v-if="item.rejectMark === 1" type="danger" size="mini">已驳回</el-tag>
                <el-tag v-else-if="item.rejectMark === 2" type="info" size="mini">已隐藏</el-tag>
                <el-tag v-else-if="item.taskStatus === 0" type="warning" size="mini">待填写</el-tag>
                <el-tag v-else-if="item.taskStatus === 1" type="success" size="mini">已完成</el-tag>
              </div>
              <div class="item-actions">
                <el-button v-if="canEdit(item)" size="mini" type="text" icon="el-icon-edit" @click.stop="handleRowClick(item)"></el-button>
                <el-button v-else size="mini" type="text" icon="el-icon-view" @click.stop="handleRowClick(item)"></el-button>
              </div>
            </div>
            <div v-if="taskList.length === 0 && !loading" class="list-empty">
              <i class="el-icon-folder-opened"></i>
              <span>暂无待处理意见</span>
            </div>
          </div>

          <div class="list-footer">
            <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
              @pagination="getList" />
          </div>
        </div>
      </template>

      <template #panelB>
        <div class="right-panel">
          <div v-if="!currentTask.taskId" class="empty-tip">
            <i class="el-icon-info"></i>
            <span>请在左侧列表中选择一条任务查看详情</span>
          </div>
          <div v-else v-loading="detailLoading" class="detail-content">
            <HeaderControlSection
              :complaintNo="acceptDetail.complaintNo"
              :flowStatus="acceptDetail.flowStatus"
              :meta="acceptDetail"
            >
              <template #actions>
                <el-button size="mini" type="text" icon="el-icon-refresh" @click="refreshDetail" title="刷新">刷新</el-button>
              </template>

              <template #basic-info>
                <BasicInfoSection :data="acceptDetail" />
              </template>

              <template #flow-overview>
                <FlowOverviewSection :flowStatus="acceptDetail.flowStatus" />
              </template>

              <template #contract-info>
                <ContractInfoSection :coilList="dialogCoilList" />
              </template>
            </HeaderControlSection>

            <el-divider />

            <CoilInfoSection :coilList="dialogCoilList" :loading="coilLoading" :editable="false" />

            <div v-if="currentTask.taskStatus === 1 && opinionForm.deptOpinion" class="section-gap" />
            <div v-if="currentTask.taskStatus === 1 && opinionForm.deptOpinion" class="opinion-preview-wrapper">
              <div class="section-title">
                <span>已提交意见 <span class="en-sub">· Submitted Opinion</span></span>
              </div>
              <DeptOpinionPreview :deptId="currentTask.deptId" :jsonData="opinionForm.deptOpinion" />
              <div v-if="opinionForm.fillFile" class="opinion-file" style="margin-top:8px;">
                <FileList :ossIds="opinionForm.fillFile" />
              </div>
            </div>

            <div v-if="isEditable" class="section-gap" />
            <div v-if="isEditable" class="opinion-form-wrapper">
              <div class="opinion-form-section">
                <div class="section-title">
                  <span>{{ currentTask.taskStatus === 1 ? '修改处理意见' : '填写处理意见' }} <span class="en-sub">· {{ currentTask.taskStatus === 1 ? 'Edit Opinion' : 'Fill in Opinion' }}</span></span>
                </div>
                <el-form ref="opinionForm" :model="opinionForm" label-width="100px">
                  <DeptOpinionForm :deptId="currentTask.deptId" :jsonData="opinionForm.deptOpinion" @input="val => opinionForm.deptOpinion = val" />
                  <el-form-item label="意见文件">
                    <file-upload v-model="opinionForm.fillFile" />
                  </el-form-item>
                </el-form>
                <div class="form-actions">
                  <el-button :loading="rejectLoading" type="danger" @click="handleReject">驳 回</el-button>
                  <el-button :loading="submitLoading" type="primary" @click="submitOpinion">提 交</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </DragResizePanel>
  </div>
</template>

<script>
import { listComplaintTask, getComplaintTask, updateComplaintTask } from "@/api/flow/complaintTask";
import { getComplaintAccept, opinionReject } from "@/api/flow/complaintAccept";
import { listAcceptCoilRel } from "@/api/flow/acceptCoilRel";
import DragResizePanel from "@/components/DragResizePanel/index.vue";
import HeaderControlSection from "./components/HeaderControlSection.vue";
import BasicInfoSection from "./components/BasicInfoSection.vue";
import CoilInfoSection from "./components/CoilInfoSection.vue";
import ContractInfoSection from "./components/ContractInfoSection.vue";
import FlowOverviewSection from "./components/FlowOverviewSection.vue";
import DeptOpinionForm from "./components/DeptOpinionForm.vue";
import DeptOpinionPreview from "./components/DeptOpinionPreview.vue";
import FileList from "@/components/FileList/index.vue";

export default {
  name: "AftermarketOpinion",
  components: { DragResizePanel, HeaderControlSection, BasicInfoSection, CoilInfoSection, ContractInfoSection, FlowOverviewSection, DeptOpinionForm, DeptOpinionPreview, FileList },
  data() {
    return {
      loading: false,
      detailLoading: false,
      coilLoading: false,
      submitLoading: false,
      rejectLoading: false,
      total: 0,

      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        complaintNo: undefined,
        taskStatus: undefined
      },
      taskList: [],
      opinionForm: { deptOpinion: '', fillFile: '' },
      acceptDetail: {},
      dialogCoilList: [],
      currentTask: {},
      isEditable: false
    };
  },
  created() {
    this.queryParams.deptId = this.$route.query.deptId != null ? Number(this.$route.query.deptId) : 1;
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      const params = { ...this.queryParams, rejectMark: 0 };
      if (params.taskStatus === '' || params.taskStatus === undefined) {
        delete params.taskStatus;
      }
      listComplaintTask(params).then(response => {
        this.total = response.total;
        this.taskList = response.rows || [];
      }).catch(() => {
        this.total = 0;
        this.taskList = [];
      }).finally(() => { this.loading = false; });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams.complaintNo = undefined;
      this.queryParams.taskStatus = undefined;
      this.handleQuery();
    },
    handleRowClick(row) {
      this.currentTask = row;
      this.isEditable = this.canEdit(row);
      this.opinionForm = { deptOpinion: '', fillFile: '' };
      this.detailLoading = true;
      this.coilLoading = true;
      this.dialogCoilList = [];
      this.acceptDetail = row.acceptInfo || {};

      listAcceptCoilRel({ acceptId: row.acceptId, pageNum: 1, pageSize: 999 }).then(r => {
        this.dialogCoilList = r.rows || [];
      }).finally(() => { this.coilLoading = false; this.detailLoading = false; });

      getComplaintTask(row.taskId).then(response => {
        const task = response.data || {};
        this.opinionForm = {
          deptOpinion: task.deptOpinion || '',
          fillFile: task.fillFile || ''
        };
      });
    },
    refreshDetail() {
      if (!this.currentTask.acceptId) return;
      this.detailLoading = true;
      this.coilLoading = true;
      getComplaintAccept(this.currentTask.acceptId).then(response => {
        this.acceptDetail = response.data || {};
      }).finally(() => { this.detailLoading = false; });
      listAcceptCoilRel({ acceptId: this.currentTask.acceptId, pageNum: 1, pageSize: 999 }).then(r => {
        this.dialogCoilList = r.rows || [];
      }).finally(() => { this.coilLoading = false; });
    },
    getDeptLabel() {
      const map = { 1: '生产部', 2: '质量部', 3: '销售部' };
      return map[this.queryParams.deptId] || '';
    },
    canEdit(row) {
      const status = (row.acceptInfo || {}).flowStatus;
      return status === 2;
    },
    confirmCancel() {
      this.$modal.confirm('确认取消？已填写的内容将不会保存。').then(() => {
        this.currentTask = {};
      }).catch(() => {});
    },
    handleReject() {
      this.$prompt('请输入驳回意见', '意见驳回', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputValidator: (val) => val ? true : '驳回意见不能为空'
      }).then(({ value }) => {
        this.rejectLoading = true;
        return opinionReject(this.currentTask.taskId, value);
      }).then(() => {
        this.$modal.msgSuccess("驳回成功");
        this.getList();
        this.currentTask = {};
      }).catch(() => { }).finally(() => { this.rejectLoading = false; });
    },
    submitOpinion() {
      try {
        const data = JSON.parse(this.opinionForm.deptOpinion || '{}');
        const hasContent = Object.values(data).some(v => v);
        if (!hasContent) {
          this.$modal.msgWarning("请至少填写一项处理意见");
          return;
        }
      } catch (e) {
        this.$modal.msgWarning("请填写处理意见");
        return;
      }
      this.submitLoading = true;
      updateComplaintTask({
        taskId: this.currentTask.taskId,
        acceptId: this.currentTask.acceptId,
        deptId: this.currentTask.deptId,
        deptOpinion: this.opinionForm.deptOpinion,
        fillFile: this.opinionForm.fillFile,
        taskStatus: 1,
        fillTime: this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
      }).then(() => {
        this.$modal.msgSuccess("意见提交成功");
        this.getList();
        this.currentTask = {};
      }).finally(() => { this.submitLoading = false; });
    }
  }
};
</script>

<style scoped>
.objection-container {
  height: calc(100vh - 84px);
}

/* ========== 左侧面板（复用 index.vue 风格） ========== */
.left-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #f5f7fa;
  border-right: 1px solid #e4e7ed;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 14px 8px;
  background: #f5f7fa;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.header-title i {
  color: #409eff;
  font-size: 16px;
}

.header-filter {
  width: 120px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 0 14px 10px;
  background: #f5f7fa;
}

.list-body {
  flex: 1;
  overflow-y: auto;
  padding: 0 6px;
}

.list-item {
  display: flex;
  align-items: center;
  padding: 10px 12px;
  margin-bottom: 2px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.15s;
}

.list-item:hover {
  background: #ebeef5;
}

.list-item.active {
  background: #d9ecff;
}

.list-item.active .item-title {
  color: #409eff;
  font-weight: 600;
}

.item-main {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.item-title {
  font-size: 13px;
  font-weight: 500;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-sub {
  font-size: 12px;
  color: #909399;
}

.item-meta {
  flex-shrink: 0;
  margin: 0 8px;
}

.item-actions {
  flex-shrink: 0;
  opacity: 0;
  transition: opacity 0.15s;
}

.list-item:hover .item-actions {
  opacity: 1;
}

.list-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #c0c4cc;
  font-size: 13px;
  gap: 8px;
}

.list-empty i {
  font-size: 32px;
}

.list-footer {
  border-top: 1px solid #e4e7ed;
  padding: 2px 8px 0;
  background: #f5f7fa;
}

/* ========== 右侧面板（复用 index.vue 风格） ========== */
.right-panel {
  height: 100%;
  overflow-y: auto;
  padding: 12px 16px;
  background: #faf8f5;
}

.right-panel .detail-content {
  margin: 0 auto;
  background: #ffffff;
  padding: 28px 32px 36px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06), 0 2px 12px rgba(0,0,0,0.04);
  min-height: 100%;
}

.empty-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
  gap: 8px;
}

/* section-title 与 index.vue 统一 */
.section-title {
  font-family: 'Georgia', 'Times New Roman', 'Noto Serif SC', 'SimSun', serif;
  width: 100%;
  font-size: 15px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 22px 0 12px 0;
  padding: 0 0 10px 0;
  border-bottom: 1px solid #d4d0c8;
  display: flex;
  align-items: center;
  gap: 10px;
  letter-spacing: 0.3px;
}

.section-title:first-child {
  margin-top: 0;
}

.section-title .en-sub {
  font-size: 11px;
  font-weight: 400;
  color: #8c8c8c;
  letter-spacing: 0.5px;
  font-family: 'Georgia', 'Times New Roman', serif;
  font-style: italic;
}

.section-gap {
  height: 16px;
}

/* ========== 意见填写区 ========== */
.opinion-form-wrapper {
  padding-top: 4px;
}

.opinion-preview-wrapper {
  padding-top: 4px;
}

.opinion-form-section {
  margin-bottom: 0;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 16px 0 0;
  border-top: 1px solid #e0dcd6;
  margin-top: 12px;
}

/* el-divider 样式与 index.vue 统一 */
.right-panel .el-divider--horizontal {
  margin: 8px 0 4px;
  background-color: #e0dcd6;
}
</style>
