<template>
  <div class="app-container">
    <!-- 对话框(查看 / 回复) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="65%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <!-- 政策标题（单行） -->
        <el-form-item label="政策标题" prop="policyTitle">
          <el-input v-model="formData.policyTitle" placeholder="请输入政策标题" disabled />
        </el-form-item>

        <el-form-item label="沟通主题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入沟通主题" disabled />
        </el-form-item>

        <!-- 沟通内容（单行） -->
        <el-form-item label="沟通内容">
          <!-- 只读模式显示 -->
          <div class="readonly-content" v-if="formData.content" v-html="formData.content"></div>
          <div class="empty-content" v-else>无内容</div>
        </el-form-item>

        <!-- 第一行：两个一排 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="沟通类型" prop="submitType">
              <el-select v-model="formData.submitType" placeholder="请选择沟通类型" disabled style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.TRS_SUBMIT_TYPE)"
                           :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提交时间" prop="submitTime">
              <el-date-picker
                style="width: 100%"
                clearable
                v-model="formData.submitTime"
                type="datetime"
                value-format="timestamp"
                placeholder="选择提交时间"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：两个一排 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="userName">
              <el-input v-model="formData.userName" placeholder="请输入用户姓名" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="mobile">
              <el-input v-model="formData.mobile" placeholder="请输入联系电话" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 附件查看（单行） -->
<!--        <el-form-item label="附件">
          <div v-if="fileList.length === 0" class="empty-attachment">
          </div>
          <div v-else class="attachment-list">
            <div v-for="(file, index) in fileList" :key="index" class="attachment-item">
              <i class="el-icon-document"></i>
              <span class="file-name" :title="file.name">{{ file.name }}</span>
              <el-button type="text" size="mini" @click="handlePreview(file)">查看</el-button>
              <el-button type="text" size="mini" @click="handleDownload(file)">下载</el-button>
            </div>
          </div>
        </el-form-item>-->
        <!-- 是否公开信息（单行） -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="是否公开" prop="submitIsPublic">
              <span v-if="formData.submitIsPublic === 0" style="color: #ff4d4f;font-weight: bold">
                用户不同意公开
              </span>
              <span v-else-if="formData.submitIsPublic === 1" style="color: green;font-weight: bold">
                用户同意公开
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 分隔线 -->
        <el-divider>回复信息</el-divider>

        <!-- 第四行：答复单位（单行或与其他字段组合） -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="回复时间" prop="replayTime">
              <el-date-picker
                style="width: 100%"
                clearable
                v-model="formData.replayTime"
                type="datetime"
                value-format="timestamp"
                placeholder="选择回复时间"
                :disabled="isReadonly || isRejectMode"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否公开" prop="replayIsPublic">
              <el-tooltip
                v-if="formData.submitIsPublic === 0"
                content="用户已选择不公开，系统强制设置为不公开"
                placement="top"
              >
                <el-radio-group
                  v-model="formData.replayIsPublic"
                  :disabled="!canEditPublic || isReadonly || isRejectMode"
                  style="padding-top:10px"
                >
                  <el-radio
                    v-for="dict in this.getDictDatas(DICT_TYPE.TRS_IS_PUBLIC)"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                    :disabled="true"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-tooltip>
              <el-radio-group
                v-else
                v-model="formData.replayIsPublic"
                :disabled="!canEditPublic || isReadonly || isRejectMode"
                style="padding-top:10px"
              >
                <el-radio
                  v-for="dict in this.getDictDatas(DICT_TYPE.TRS_IS_PUBLIC)"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>

        <!-- 回复内容（只有在非不予办理模式下显示） -->
        <el-form-item
          :label="formData.dealStatus === 3 ? '不予办理理由' : '回复内容'"
          prop="replayContent"
          v-if="!isRejectMode || isReadonly"
        >
          <!-- 查看模式下显示已有内容 -->
          <div v-if="isReadonly" class="readonly-content">
            <div v-if="formData.dealStatus === 3 && formData.rejectReason">
              <!-- 不予办理记录显示不予办理理由 -->
              {{ formData.rejectReason }}
            </div>
            <div v-else-if="formData.replayContent" v-html="formData.replayContent"></div>
            <div v-else class="empty-content">无内容</div>
          </div>

          <!-- 办理模式下显示编辑器 -->
          <Editor
            v-else
            v-model="formData.replayContent"
            :min-height="192"
            :readonly="isReadonly || isRejectMode"
            placeholder="请输入回复内容"
          />
        </el-form-item>

        <!-- 不予办理理由输入框（只有在办理模式下的不予办理模式下显示） -->
        <el-form-item label="不予办理理由" prop="rejectReason" v-if="isRejectMode && !isReadonly">
          <el-input
            v-model="formData.rejectReason"
            type="textarea"
            :rows="4"
            placeholder="请输入不予办理的理由"
            maxlength="500"
            show-word-limit
            :disabled="isReadonly"
          />
        </el-form-item>

        <!-- 不予办理模式提示 -->
        <div v-if="isRejectMode && !isReadonly" class="reject-mode-tip">
          <i class="el-icon-warning-outline"></i> 不予办理模式下，只需填写不予办理理由，系统将自动标记为不予办理状态。
        </div>

        <!-- 查看不予办理记录时的提示 -->
        <div v-if="isReadonly && formData.dealStatus === 3" class="reject-view-tip">
          <i class="el-icon-warning-outline"></i> 此记录为不予办理记录。
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- 查看模式下只有关闭按钮 -->
        <el-button v-if="isReadonly" @click="dialogVisible = false">关 闭</el-button>

        <!-- 办理模式下显示三个按钮 -->
        <template v-else>
          <el-button
            type="primary"
            @click="submitForm('approve')"
            :disabled="formLoading"
            v-if="!isRejectMode"
          >
            确认答复
          </el-button>
          <el-button
            type="warning"
            @click="switchToRejectMode"
            :disabled="formLoading || isRejectMode"
            v-if="!isRejectMode"
          >
            不予办理
          </el-button>
          <el-button
            type="warning"
            @click="submitForm('reject')"
            :disabled="formLoading"
            v-if="isRejectMode"
          >
            确认不予办理
          </el-button>
          <el-button
            @click="cancelRejectMode"
            v-if="isRejectMode"
            :disabled="formLoading"
          >
            返回答复
          </el-button>
          <el-button @click="dialogVisible = false">关 闭</el-button>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as PolicyCommunicationsApi from '@/api/server/policycommunications';
import FileUpload from '@/components/FileUpload';
import Editor from '@/components/Editor';

export default {
  name: "PolicyCommunicationsForm",
  components: {
    FileUpload,
    Editor
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 是否为只读模式（查看模式）
      isReadonly: false,
      // 是否可以编辑是否公开
      canEditPublic: false,
      // 文件列表
      fileList: [],
      // 是否处于不予办理模式
      isRejectMode: false,
      // 对话框模式（查看、办理、修改）
      dialogMode: 'view',
      // 表单参数
      formData: {
        id: undefined,
        policyId: undefined,
        policyTitle: undefined,
        replyDept: undefined,
        replyDeptid: undefined,
        userName: undefined,
        userId: undefined,
        mobile: undefined,
        submitType: undefined,
        title: undefined,
        content: undefined,
        msg: undefined,
        submitTime: undefined,
        submitIsPublic: undefined,
        attachment: undefined,
        dealStatus: undefined,
        replayContent: undefined,
        replayTime: undefined,
        replayIsPublic: undefined,
        rejectReason: undefined,
      },
      // 表单校验
      formRules: {
        replayContent: [
          {
            required: true,
            message: '回复内容不能为空',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              // 只有在非不予办理模式下才需要验证回复内容
              if (!this.isRejectMode && !value) {
                callback(new Error('回复内容不能为空'));
              } else {
                callback();
              }
            }
          }
        ],
        replayTime: [
          {
            required: true,
            message: '回复时间不能为空',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              // 只有在非不予办理模式下才需要验证回复时间
              if (!this.isRejectMode && !value) {
                callback(new Error('回复时间不能为空'));
              } else {
                callback();
              }
            }
          }
        ],
        replayIsPublic: [
          {
            required: true,
            message: '请选择是否公开',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              // 只有在非不予办理模式下才需要验证是否公开
              if (!this.isRejectMode && value === undefined) {
                callback(new Error('请选择是否公开'));
              } else {
                callback();
              }
            }
          }
        ],
        // 新增：不予办理理由的验证
        rejectReason: [
          {
            required: true,
            message: '不予办理理由不能为空',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              // 只有在不予办理模式下才需要验证理由
              if (this.isRejectMode && !value) {
                callback(new Error('不予办理理由不能为空'));
              } else {
                callback();
              }
            }
          },
          {
            min: 2,
            message: '不予办理理由至少需要2个字符',
            trigger: 'blur'
          }
        ]
      },
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(id, readonly = false, mode = 'view') {
      this.dialogVisible = true;
      this.isReadonly = readonly;
      this.dialogMode = mode;
      this.isRejectMode = false; // 重置不予办理模式

      // 根据模式设置标题
      if (readonly) {
        this.dialogTitle = "查看政策沟通交流";
      } else if (mode === 'process') {
        this.dialogTitle = "办理政策沟通交流";
      } else {
        this.dialogTitle = "修改政策沟通交流";
      }

      this.reset();

      // 加载数据
      this.formLoading = true;
      try {
        const res = await PolicyCommunicationsApi.getPolicyCommunications(id);
        const data = res.data;

        // 根据 submitIsPublic 设置是否可以编辑公开状态
        this.canEditPublic = data.submitIsPublic === 1;

        // 检查是否为不予办理记录
        const isRejectedRecord = data.dealStatus === 3;

        // 设置回复是否公开的默认值
        let defaultReplayIsPublic;
        if (data.submitIsPublic === 0) {
          // 如果用户提交时选择不公开，回复也不公开且不可编辑
          defaultReplayIsPublic = 0;
        } else if (isRejectedRecord) {
          // 如果是不予办理记录，默认不公开
          defaultReplayIsPublic = 0;
        } else {
          // 如果用户提交时选择公开，回复默认公开且可编辑
          defaultReplayIsPublic = data.replayIsPublic !== undefined ? data.replayIsPublic : 1;
        }

        // 设置表单数据
        this.formData = {
          id: data.id,
          policyId: data.policyId,
          policyTitle: data.policyTitle,
          replyDept: data.replyDept,
          replyDeptid: data.replyDeptid,
          userName: data.userName,
          userId: data.userId,
          mobile: data.mobile,
          submitType: data.submitType,
          title: data.title,
          content: data.content,
          msg: data.msg,
          submitTime: data.submitTime,
          submitIsPublic: data.submitIsPublic,
          attachment: data.attachment,
          dealStatus: data.dealStatus,
          // 如果不予办理记录，将rejectReason显示在replayContent位置
          replayContent: isRejectedRecord && data.rejectReason ? data.rejectReason : data.replayContent,
          replayTime: data.replayTime || new Date().getTime(),
          replayIsPublic: defaultReplayIsPublic,
          rejectReason: data.rejectReason,
        };

        // 处理附件
        this.parseAttachment(data.attachment);

      } finally {
        this.formLoading = false;
      }
    },

    /** 解析附件 */
    parseAttachment(attachment) {
      this.fileList = [];
      if (!attachment) return;

      const paths = attachment.split(',').filter(path => path.trim());
      paths.forEach((path, index) => {
        const fileName = path.split('/').pop() || `附件${index + 1}`;
        this.fileList.push({
          name: fileName,
          url: path,
          status: 'success'
        });
      });
    },

    /** 附件查看 */
    handlePreview(file) {
      if (file.url) {
        window.open(file.url, '_blank');
      }
    },

    /** 附件下载 */
    handleDownload(file) {
      if (file.url) {
        const link = document.createElement('a');
        link.href = file.url;
        link.download = file.name;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },

    /** 切换到不予办理模式 */
    switchToRejectMode() {
      this.isRejectMode = true;
      // 清空回复内容，因为不予办理模式下不需要回复内容
      this.formData.replayContent = '';
      // 不予办理时默认设置为不公开
      this.formData.replayIsPublic = 0;
      this.dialogTitle = "不予办理政策沟通交流";
    },

    /** 取消不予办理模式，返回答复模式 */
    cancelRejectMode() {
      this.isRejectMode = false;
      this.dialogTitle = this.dialogMode === 'process' ? "办理政策沟通交流" : "修改政策沟通交流";
      // 清除不予办理理由的验证状态
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate('rejectReason');
        }
      });
    },

    /** 提交按钮 */
    async submitForm(action) {
      try {
        // 验证表单
        await this.$refs["formRef"].validate();
      } catch (error) {
        console.log('表单验证失败:', error);
        return;
      }

      this.formLoading = true;
      try {
        if (action === 'approve') {
          // 正常答复
          const data = {
            id: this.formData.id,
            replayContent: this.formData.replayContent,
            replayTime: this.formData.replayTime,
            replayIsPublic: this.formData.replayIsPublic,
            // 更新处理状态
            dealStatus: 1, // 已处理
            rejectReason: null, // 清空不予办理理由
          };

          // 调用更新接口
          await PolicyCommunicationsApi.updatePolicyCommunications(data);
          this.$modal.msgSuccess("答复成功");
        } else if (action === 'reject') {
          // 不予办理
          const data = {
            id: this.formData.id,
            rejectReason: this.formData.rejectReason,
            replayTime: this.formData.replayTime,
            replayIsPublic: 0, // 不予办理时强制设置为不公开
            // 更新处理状态为拒绝
            dealStatus: 2, // 拒绝状态
            replayContent: '【不予办理】' + this.formData.rejectReason // 将理由存入回复内容
          };

          // 调用更新接口
          await PolicyCommunicationsApi.updatePolicyCommunications(data);
          this.$modal.msgSuccess("不予办理操作成功");
        }

        this.dialogVisible = false;
        this.$emit('success');
      } catch (error) {
        console.error('提交失败:', error);
        this.$modal.msgError(`操作失败: ${error.message || '未知错误'}`);
      } finally {
        this.formLoading = false;
      }
    },

    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        policyId: undefined,
        policyTitle: undefined,
        replyDept: undefined,
        replyDeptid: undefined,
        userName: undefined,
        userId: undefined,
        mobile: undefined,
        submitType: undefined,
        title: undefined,
        content: undefined,
        msg: undefined,
        submitTime: undefined,
        submitIsPublic: undefined,
        attachment: undefined,
        dealStatus: undefined,
        replayContent: undefined,
        replayTime: undefined,
        replayIsPublic: undefined,
        rejectReason: undefined,
      };
      this.fileList = [];
      this.canEditPublic = false;
      this.isRejectMode = false;
      this.dialogMode = 'view';
      this.resetForm("formRef");
    }
  }
};
</script>

<style scoped>
/* 沟通内容样式 - 调整行间距 */
.readonly-content {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  min-height: 70px;
  max-height: 250px;
  overflow-y: auto;
  background-color: #f5f7fa;
  line-height: 1.5;
  font-size: 14px;
}

/* 进一步减少富文本内容的行间距 */
.readonly-content p {
  margin: 8px 0;
  line-height: 1.5;
}

.readonly-content div {
  line-height: 1.5;
}

.empty-content {
  color: #909399;
  text-align: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
  min-height: 100px;
  line-height: 70px;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 6px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
  font-size: 13px;
}

.attachment-item:hover {
  background-color: #f5f7fa;
}

.attachment-item i {
  margin-right: 6px;
  color: #409eff;
  font-size: 14px;
}

.attachment-item .file-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 13px;
}

.empty-attachment {
  color: #909399;
  font-size: 12px;
  padding: 8px 0;
}

/* 不予办理模式提示 */
.reject-mode-tip {
  margin: 10px 0;
  padding: 10px;
  background-color: #fdf6ec;
  border: 1px solid #faecd8;
  border-radius: 4px;
  color: #e6a23c;
  font-size: 14px;
}

.reject-mode-tip i {
  margin-right: 5px;
  font-size: 16px;
}

/* 查看不予办理记录时的提示 */
.reject-view-tip {
  margin: 10px 0;
  padding: 10px;
  background-color: #fdf6ec;
  border: 1px solid #faecd8;
  border-radius: 4px;
  color: #e6a23c;
  font-size: 14px;
}

.reject-view-tip i {
  margin-right: 5px;
  font-size: 16px;
}

::v-deep .el-divider__text {
  background-color: #fff;
  font-weight: bold;
  color: #409eff;
  font-size: 14px;
  padding: 0 10px;
}

/* 只读输入框样式 */
::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
  cursor: not-allowed;
  font-size: 14px;
}

/* 调整行间距 */
.el-row {
  margin-bottom: 8px;
}

/* 调整表单项间距 */
.el-form-item {
  margin-bottom: 12px;
}

/* 标签样式 */
::v-deep .el-form-item__label {
  font-size: 14px;
  color: #606266;
  font-weight: normal;
}

/* 日期选择器样式 */
::v-deep .el-date-editor.el-input,
::v-deep .el-date-editor.el-input__inner {
  width: 100%;
}

/* 单选按钮组样式 */
::v-deep .el-radio-group {
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 编辑器样式调整 */
::v-deep .editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

::v-deep .editor-container.is-disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
}

/* 文本域计数器样式 */
::v-deep .el-textarea .el-input__count {
  background: transparent;
  color: #909399;
}

/* 不予办理理由文本域样式 */
::v-deep .el-textarea.is-disabled .el-textarea__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
  cursor: not-allowed;
}
</style>
