<template>
  <a-spin :spinning="loading">
    <div class="bg-fixcontact-bpm-form">
      <a-form
        class="main-form"
        :class="{ 'main-form-readonly': mainDisabled }"
        labelAlign="left"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        :model="mainForm"
      >
        <div class="base-info-header section-toolbar">
          <div class="section-title">基础信息</div>
          <a-space class="section-actions">
            <a-button v-if="!mainDisabled" class="base-save-button" type="link" size="small" :loading="savingMain" @click="submitForm">
              <Icon icon="ant-design:save-outlined" />
              保存
            </a-button>
            <a-button
              class="section-action-button"
              :type="showBaseInfoDetail ? 'default' : 'link'"
              size="small"
              @click="showBaseInfoDetail = !showBaseInfoDetail"
            >
              <Icon :icon="showBaseInfoDetail ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
              {{ showBaseInfoDetail ? '收起基础信息' : '展开全部信息' }}
            </a-button>
          </a-space>
        </div>
        <a-row class="base-info-row" :gutter="[12, 4]">
          <a-col :xs="24" :md="12">
            <a-form-item label="序号" name="seqNo">
              <a-input v-model:value="mainForm.seqNo" :disabled="mainDisabled" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :md="12">
            <a-form-item label="表单编号" name="formNo">
              <a-input v-model:value="mainForm.formNo" :disabled="mainDisabled" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :md="12">
            <a-form-item label="定点联系所领导" name="contactLeader">
              <DeptRoleUserSelectDropDown
                v-model:value="mainForm.contactLeader"
                :deptId="PARTY_COMMITTEE_DEPT_ID"
                :roleId="CHARGE_LEADER_ROLE_ID"
                :disabled="mainDisabled"
                placeholder="请选择定点联系所领导"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :md="12">
            <a-form-item label="联系单位（部门）" name="contactDept">
              <SzSelectDept v-model:value="mainForm.contactDept" :disabled="mainDisabled" placeholder="请选择联系单位（部门）" allow-clear />
            </a-form-item>
          </a-col>
          <template v-if="showBaseInfoDetail">
            <a-divider />
            <a-col :xs="24" :md="12">
              <a-form-item label="联系时间" name="contactTime">
                <a-date-picker v-model:value="mainForm.contactTime" value-format="YYYY-MM-DD" :disabled="mainDisabled" placeholder="请选择联系时间" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="座谈地点" name="meetingPlace">
                <a-input v-model:value="mainForm.meetingPlace" :disabled="mainDisabled" placeholder="请输入座谈地点" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="联系点建议诉求摘要" name="suggestionSummary" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
                <a-textarea v-model:value="mainForm.suggestionSummary" :auto-size="{ minRows: 1, maxRows: 7 }" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="定点联系所领导审批意见" name="leaderOpinion" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
                <a-textarea v-model:value="mainForm.leaderOpinion" :auto-size="{ minRows: 1, maxRows: 7 }" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="相关分管所领导批示意见" name="relatedLeaderOpinion" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
                <a-textarea v-model:value="mainForm.relatedLeaderOpinion" :auto-size="{ minRows: 1, maxRows: 7 }" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="相关分管所领导" name="relatedLeader">
                <DeptRoleUserSelectDropDown
                  v-model:value="mainForm.relatedLeader"
                  :deptId="PARTY_COMMITTEE_DEPT_ID"
                  :roleId="CHARGE_LEADER_ROLE_ID"
                  :disabled="mainDisabled"
                  placeholder="请选择相关分管所领导"
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="申请人" name="applicant">
                <SzSelectUser v-model:value="mainForm.applicant" :disabled="mainDisabled" placeholder="请选择申请人" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="主办部门" name="hostDept">
                <SzSelectDept v-model:value="mainForm.hostDept" :disabled="mainDisabled" placeholder="请选择主办部门" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="协办部门" name="coDept">
                <SzSelectDept v-model:value="mainForm.coDept" :disabled="mainDisabled" placeholder="请选择协办部门" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="督办次数" name="superviseCount">
                <a-input-number v-model:value="mainForm.superviseCount" :disabled="mainDisabled" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
          </template>
        </a-row>
      </a-form>

      <a-divider />

      <div class="feedback-header section-toolbar" v-if="showFeedbackInfo">
        <div class="section-title">办理情况</div>
        <a-space class="section-actions">
          <a-tooltip v-if="showAddFeedback" title="可以多次新增反馈">
            <a-button class="section-action-button feedback-add-button" type="primary" @click="openFeedbackModal">
              <Icon icon="ant-design:plus-outlined" />
              新增反馈
            </a-button>
          </a-tooltip>
          <a-button
            class="section-action-button"
            :type="showFeedbackDetail ? 'default' : 'link'"
            size="small"
            @click="showFeedbackDetail = !showFeedbackDetail"
          >
            <Icon :icon="showFeedbackDetail ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
            {{ showFeedbackDetail ? '收起办理情况' : '展开办理情况' }}
          </a-button>
        </a-space>
      </div>
      <a-table
        v-if="showFeedbackInfo && showFeedbackDetail"
        rowKey="id"
        size="small"
        bordered
        :columns="feedbackColumns"
        :data-source="feedbackList"
        :pagination="false"
        :scroll="{ x: feedbackTableScrollX }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'attachments'">
            <SUploadFile
              v-if="record.id"
              :key="getFeedbackAttachmentKey(record)"
              class="feedback-attachment-list"
              :bussiness-id="record.id"
              :disabled="true"
              :multiple="true"
            />
            <span v-else>-</span>
          </template>
          <template v-else-if="canManageFeedback && column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="openFeedbackEditModal(record)">编辑</a-button>
              <a-popconfirm title="是否确认删除" @confirm="handleFeedbackDelete(record)">
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <FixedContact20260730BPMFeedbackModal ref="feedbackModalRef" @success="loadFeedbackList" />

      <template v-if="showProcessHandle">
        <a-divider />
        <div class="process-header section-toolbar">
          <div class="section-title">流程办理</div>
        </div>
        <TaskHandleInnerContent
          :form-data="formData"
          :claim="claim"
          :showSelnextUser="showSelnextUser"
          :beforeHandle="saveMainFormBeforeProcessHandle"
          @success="handleProcessSuccess"
          @claimSuccess="handleClaimSuccess"
        />
      </template>
    </div>
  </a-spin>
</template>

<script lang="ts" setup>
  import { computed, h, onMounted, reactive, ref, watch } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { usePermission } from '/@/hooks/web/usePermission';
  import Icon from '/@/components/Icon/index';
  import SzSelectDept from '/@/components/Form/src/jeecg/components/SzSelectDept.vue';
  import SzSelectUser from '/@/components/semri/userComponent/SzUserSelect.vue';
  import DeptRoleUserSelectDropDown from '/@/components/semri/userComponent/DeptRoleUserSelectDropDown.vue';
  import SUploadFile from '/@/components/semri/fileComponent/SUploadFile.vue';
  import TaskHandleInnerContent from '/@/views/super/bpm/process/personalOffice/myHandleTask/content/TaskHandleInnerContent.vue';
  import FixedContact20260730BPMFeedbackModal from './FixedContact20260730BPMFeedbackModal.vue';
  import { fixedContactFeedbackList, saveBpmForm, setBpmVariableLocal } from '../FixedContact20260730.api';
  import { PARTY_COMMITTEE_DEPT_ID, CHARGE_LEADER_ROLE_ID } from '/@/constant/supervision';

  const { initBpmFormData } = usePermission();

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true },
    claim: { type: Boolean, default: false },
  });

  initBpmFormData(props.formData);

  const emit = defineEmits(['ok', 'success', 'claimSuccess']);
  const { createMessage } = useMessage();
  const queryByIdUrl = '/bg/fixcontact/fixedContact20260730/queryById';

  const labelCol = { xs: { span: 24 }, sm: { span: 7 } };
  const wrapperCol = { xs: { span: 24 }, sm: { span: 17 } };
  const wideLabelCol = { xs: { span: 24 }, sm: { span: 3 } };
  const wideWrapperCol = { xs: { span: 24 }, sm: { span: 21 } };

  const feedbackModalRef = ref();
  const loading = ref(false);
  const savingMain = ref(false);
  const showBaseInfoDetail = ref(false);
  const showFeedbackDetail = ref(true);
  const feedbackList = ref<any[]>([]);
  const feedbackAttachmentRefreshKey = ref(0);

  const mainForm = reactive<Record<string, any>>({
    id: '',
    seqNo: '',
    formNo: '',
    contactLeader: '',
    contactDept: '',
    contactTime: '',
    meetingPlace: '',
    suggestionSummary: '',
    leaderOpinion: '',
    relatedLeaderOpinion: '',
    relatedLeader: '',
    applicant: '',
    hostDept: '',
    coDept: '',
    superviseCount: '',
  });

  function renderWrappedCell({ text }: Recordable) {
    return h('div', { style: 'white-space: pre-wrap; word-break: break-word;' }, text ?? '');
  }

  const feedbackBaseColumns = [
    { title: '反馈部门', dataIndex: 'feedbackDept_dictText', align: 'center', width: 160 },
    { title: '反馈人', dataIndex: 'feedbackUser_dictText', align: 'center', width: 120 },
    { title: '计划完成时间', dataIndex: 'planFinishTime', align: 'center', width: 130, customRender: ({ text }) => (!text ? '' : String(text).slice(0, 10)) },
    { title: '计划完成情况', dataIndex: 'planFinishStatus', align: 'left', width: 260, customRender: renderWrappedCell },
    { title: '处理意见、承办情况', dataIndex: 'handleOpinion', align: 'left', width: 260, customRender: renderWrappedCell },
    { title: '办结情况', dataIndex: 'finishStatus', align: 'left', width: 200, customRender: renderWrappedCell },
    { title: '实际完成时间', dataIndex: 'actualFinishTime', align: 'center', width: 130, customRender: ({ text }) => (!text ? '' : String(text).slice(0, 10)) },
    { title: '实际完成情况', dataIndex: 'actualFinishStatus', align: 'left', width: 200, customRender: renderWrappedCell },
    { title: '附件', dataIndex: 'id', key: 'attachments', align: 'left', width: 340 },
  ];
  const feedbackActionColumn = { title: '操作', dataIndex: 'action', key: 'action', align: 'center', width: 120, fixed: 'right' };
  const feedbackColumns = computed(() => {
    return canManageFeedback.value ? [...feedbackBaseColumns, feedbackActionColumn] : feedbackBaseColumns;
  });
  const feedbackTableScrollX = computed(() => {
    return canManageFeedback.value ? 1920 : 1800;
  });

  const mainDisabled = computed(() => {
    if (props.formBpm) {
      return props.formData?.disabled !== false;
    }
    return props.formDisabled;
  });
  const showProcessHandle = computed(() => {
    const explicit = props.formData?.extendUrlParams?.showProcessHandle;
    if (explicit === '0') return false;
    if (explicit === '1') return true;
    return props.formBpm && props.formData?.PROCESS_TAB_TYPE === 'run' && !!props.formData?.taskId;
  });
  const canManageFeedback = computed(() => {
    const explicit = props.formData?.extendUrlParams?.showEditFeedback ?? props.formData?.extendUrlParams?.editfeedback;
    if (explicit === '0') return false;
    if (explicit === '1') return true;
    return props.formBpm && props.formData?.PROCESS_TAB_TYPE === 'run' && !!props.formData?.taskId;
  });
  const showAddFeedback = computed(
    () => String(props.formData?.extendUrlParams?.showAddFeedback ?? props.formData?.extendUrlParams?.addfeedback ?? '') === '1'
  );

  const processInfo = computed(() => ({
    taskId: props.formData?.taskId,
    taskDefKey: props.formData?.taskDefKey,
    processInstanceId:
      props.formData?.procInsId ||
      props.formData?.procInstId ||
      props.formData?.processInstanceId ||
      props.formData?.vars?.BPM_INST_ID ||
      props.formData?.vars?.JG_LOCAL_PROCESS_ID ||
      props.formData?.vars?.process_inst_id ||
      props.formData?.vars?.processInstanceId,
    processDataId: props.formData?.processDataId,
    processTableName: props.formData?.processTableName,
  }));
  const showFeedbackInfo = computed(() => {
    const explicit = props.formData?.extendUrlParams?.showFeedbackInfo;
    if (explicit === '0') return false;
    if (explicit === '1') return true;
    const hasProcess = processInfo.value.taskId || processInfo.value.processInstanceId;
    return !!hasProcess;
  });
  const showSelnextUser = computed(() => String(props.formData?.extendUrlParams?.showSelnextUser ?? '') === '1');

  onMounted(() => {
    initFormData();
  });

  watch([() => props.formData?.dataId, () => processInfo.value.processInstanceId], () => initFormData());

  async function initFormData() {
    const dataId = props.formData?.dataId;
    if (!dataId) {
      return;
    }
    showBaseInfoDetail.value = false;
    loading.value = true;
    try {
      const data = await defHttp.get({ url: queryByIdUrl, params: { id: dataId } });
      if (dataId !== props.formData?.dataId) {
        return;
      }
      setMainForm(data || {});
      if (dataId !== props.formData?.dataId) {
        return;
      }
      await loadFeedbackList();
    } finally {
      loading.value = false;
    }
  }

  function setMainForm(record: Record<string, any>) {
    Object.keys(mainForm).forEach((key) => {
      mainForm[key] = record[key] ?? '';
    });
  }

  async function loadFeedbackList() {
    const bpmProcessId = processInfo.value.processInstanceId;
    if (!mainForm.id || !bpmProcessId) {
      feedbackList.value = [];
      feedbackAttachmentRefreshKey.value += 1;
      return;
    }
    const res = await fixedContactFeedbackList({ id: mainForm.id, bpmProcessId });
    feedbackList.value = res?.records || res?.result?.records || [];
    feedbackAttachmentRefreshKey.value += 1;
  }

  function getFeedbackAttachmentKey(record: Recordable) {
    return `${record?.id || ''}-${feedbackAttachmentRefreshKey.value}`;
  }

  async function submitForm() {
    return saveMainForm();
  }

  async function saveMainForm(options: { showMessage?: boolean; emitOk?: boolean } = {}) {
    const { showMessage = true, emitOk = true } = options;
    savingMain.value = true;
    try {
      const processInstanceId = processInfo.value.processInstanceId;
      const res = await saveBpmForm({
        processInstanceId,
        varField: 'json_data',
        formData: { ...mainForm },
      });
      if (res.success) {
        if (showMessage) {
          createMessage.success(res.message || '保存成功');
        }
        if (emitOk) {
          emit('ok');
        }
        return true;
      }
      createMessage.warning(res.message || '保存失败');
      return false;
    } catch (error) {
      createMessage.warning('保存失败');
      return false;
    } finally {
      savingMain.value = false;
    }
  }

  async function saveMainFormBeforeProcessHandle() {
    if (!mainDisabled.value) {
      const mainSaved = await saveMainForm({ showMessage: false, emitOk: false });
      if (!mainSaved) {
        return false;
      }
    }
    return true;
  }

  function openFeedbackModal() {
    if (!mainForm.id) {
      createMessage.warning('主表数据不存在，无法新增反馈');
      return;
    }
    const processInstanceId = processInfo.value.processInstanceId;
    if (!processInstanceId) {
      createMessage.warning('流程实例ID不能为空，无法新增反馈');
      return;
    }
    feedbackModalRef.value?.open(mainForm.id, processInstanceId);
  }

  function openFeedbackEditModal(record: Recordable) {
    if (!canManageFeedback.value) {
      createMessage.warning('当前流程状态不允许编辑反馈');
      return;
    }
    if (!record?.id) {
      createMessage.warning('反馈记录不存在，无法编辑');
      return;
    }
    feedbackModalRef.value?.open(mainForm.id, processInfo.value.processInstanceId, record);
  }

  async function handleFeedbackDelete(record: Recordable) {
    if (!canManageFeedback.value) {
      createMessage.warning('当前流程状态不允许删除反馈');
      return;
    }
    if (!record?.id) {
      createMessage.warning('反馈记录不存在，无法删除');
      return;
    }
    try {
      await defHttp.delete({ url: '/bg/fixcontact/fixedContact20260730/deleteFixedContactFeedback20260730', params: { id: record.id } });
      createMessage.success('删除成功');
      await loadFeedbackList();
    } catch (error) {
      createMessage.warning('删除失败');
    }
  }

  function handleProcessSuccess() {
    emit('success');
  }

  function handleClaimSuccess() {
    emit('claimSuccess');
  }

  defineExpose({
    submitForm,
    initFormData,
    loadFeedbackList,
  });
</script>

<style lang="less" scoped>
  .bg-fixcontact-bpm-form {
    padding: 8px 12px 14px;
  }

  .main-form {
    background: #fff;
  }

  .main-form,
  .process-variable-form {
    :deep(.ant-form-item-label) {
      text-align: left;
    }

    :deep(.ant-form-item-label > label) {
      justify-content: flex-start;
      color: #1f2937;
      font-weight: 500;
    }

    :deep(.ant-form-item-control),
    :deep(.ant-form-item-control-input),
    :deep(.ant-form-item-control-input-content) {
      text-align: left;
    }
  }

  .section-title {
    margin-bottom: 8px;
    padding-left: 8px;
    border-left: 3px solid #1677ff;
    color: #1f2937;
    font-size: 14px;
    font-weight: 600;
    line-height: 16px;
  }

  .section-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
    padding: 6px 10px;
    background: #f6fbff;
    border: 1px solid #d6e8ff;
    border-radius: 6px;

    .section-title {
      margin-bottom: 0;
    }

    .section-actions {
      display: inline-flex;
      align-items: center;
      gap: 4px;
    }

    .section-action-button {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      min-width: 58px;
      justify-content: center;
      font-weight: 500;
      box-shadow: none;
    }

    .base-save-button {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      height: 24px;
      padding: 0 6px;
      color: #64748b;
      font-weight: 400;
    }
  }

  .base-info-header {
    margin-top: 0;
  }

  .base-info-row {
    padding: 0 10px;

    :deep(.ant-form-item) {
      margin-bottom: 6px;
    }

    :deep(.ant-form-item-label) {
      padding-bottom: 0;
    }

    :deep(.ant-form-item-label > label) {
      width: 100%;
    }

    :deep(.ant-input),
    :deep(.ant-input-affix-wrapper),
    :deep(.ant-input-number),
    :deep(.ant-picker),
    :deep(.ant-select-selector) {
      min-height: 30px;
    }
  }

  .main-form-readonly {
    :deep(.ant-input[disabled]),
    :deep(.ant-input-disabled),
    :deep(.ant-input-affix-wrapper-disabled),
    :deep(.ant-input-affix-wrapper-disabled.ant-input-outlined),
    :deep(.ant-input-number-disabled),
    :deep(.ant-input-outlined[disabled]),
    :deep(.ant-input-outlined.ant-input-disabled),
    :deep(textarea.ant-input[disabled]),
    :deep(.ant-picker-disabled),
    :deep(.ant-select-disabled .ant-select-selector) {
      background: transparent !important;
      border-color: transparent !important;
      color: #1f2937 !important;
      box-shadow: none !important;
      cursor: default !important;
      opacity: 1 !important;
    }

    :deep(.ant-input[disabled]),
    :deep(.ant-input-disabled),
    :deep(.ant-input-number-disabled),
    :deep(.ant-input-affix-wrapper-disabled),
    :deep(textarea.ant-input[disabled]) {
      padding-left: 0 !important;
      padding-right: 0 !important;
    }

    :deep(.ant-input-number-disabled .ant-input-number-input) {
      background: transparent !important;
      color: #1f2937 !important;
      -webkit-text-fill-color: #1f2937 !important;
      cursor: default !important;
    }

    :deep(.ant-picker-disabled),
    :deep(.ant-select-disabled .ant-select-selector) {
      padding-left: 0 !important;
    }

    :deep(.ant-select-disabled .ant-select-arrow),
    :deep(.ant-picker-disabled .ant-picker-suffix),
    :deep(.ant-input-disabled .ant-input-clear-icon),
    :deep(.ant-input-affix-wrapper-disabled .ant-input-clear-icon),
    :deep(.ant-input-number-disabled .ant-input-number-handler-wrap),
    :deep(.ant-select-disabled .ant-select-clear) {
      display: none;
    }
  }

  .feedback-header {
    margin-bottom: 8px;

    .feedback-add-button {
      min-width: 104px;
    }
  }

  :deep(.ant-divider-horizontal) {
    margin: 10px 0;
  }

  .feedback-attachment-list {
    min-width: 300px;

    :deep(.file-list-wrapper) {
      min-height: 0 !important;
      padding: 4px 8px;
    }

    :deep(.ant-spin-nested-loading),
    :deep(.ant-spin-container) {
      min-height: 0 !important;
      line-height: 20px;
    }

    :deep(.file-list-header) {
      margin-bottom: 6px;
      padding-bottom: 6px;
    }

    :deep(.file-list .file-item) {
      padding: 8px;
      margin-bottom: 6px;
    }

    :deep(.ant-empty) {
      margin: 0 !important;
      display: flex;
      align-items: center;
      min-height: 20px;
      text-align: left;
    }

    :deep(.ant-empty-image) {
      display: none !important;
    }

    :deep(.ant-empty-description) {
      color: #94a3b8;
      font-size: 12px;
      line-height: 20px;
    }
  }
</style>
