<template>
  <a-card class="general-card" title="交付物清单" style="margin-top: 8px">
    <div class="item-container">
      <a-form
        ref="outcomeFormRef"
        :model="addOutcomeParams"
        :auto-label-width="true"
        label-align="right"
      >
        <a-table
          style="padding: 0 16px"
          :columns="tableColumns"
          :data="outcomeList"
          :table-layout-fixed="true"
          :pagination="false"
          :bordered="true"
          :hoverable="false"
        >
          <template #index="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
          <template #status="{ record }">
            <a-tag v-if="record.isCreated" color="pinkpurple">待添加</a-tag>
            <a-tag v-else :color="outcomeStatus(record.status)?.color">{{
              outcomeStatus(record.status)?.label
            }}</a-tag>
          </template>
          <template #name="{ record }">
            <a-form-item
              v-if="record.isCreated"
              no-style
              feedback
              :field="`name`"
              :validate-trigger="['change', 'input']"
              :rules="{
                required: true
              }"
            >
              <a-input
                v-model="addOutcomeParams.name"
                placeholder="交付物名称"
              />
            </a-form-item>
            <HoverEditorDetail
              v-else
              v-model="record.name"
              placeholder="交付物名称"
              :not-allow-null="true"
              :old-value="toRaw(record.name)"
              :components-type="ComponentsType.STRINGINPUT"
              @modify="
                oldValue =>
                  handleModifyOutcomeName(
                    record.id,
                    record.name,
                    oldValue,
                    record
                  )
              "
            />
          </template>
          <template #plan_time="{ record }">
            <a-form-item
              v-if="record.isCreated"
              no-style
              feedback
              :field="`plan_time`"
              :validate-trigger="['change', 'input']"
              :rules="{
                required: true
              }"
            >
              <a-date-picker
                v-model="addOutcomeParams.plan_time"
                :style="{ width: '100%' }"
                placeholder="计划时间"
              />
            </a-form-item>
            <HoverEditorDetail
              v-else
              v-model="record.plan_time"
              placeholder="计划时间"
              :not-allow-null="true"
              :old-value="toRaw(record.plan_time)"
              :components-type="ComponentsType.DATEPICKER"
              @modify="
                oldValue => handleModifyOutcomePlanTime(record, oldValue)
              "
            />
          </template>
          <template #operate="{ rowIndex, record }">
            <div v-if="!record.isCreated" class="operate-text-button">
              <div v-if="draft" class="ribbon-wrapper">
                <div
                  :class="
                    'ribbon ' + getRibbonInfo(record.change_marker)?.class
                  "
                >
                  {{ getRibbonInfo(record.change_marker)?.label }}
                </div>
              </div>
              <a-button
                type="text"
                @click="redirectOutcomeDetailPage(record.id)"
                >详情</a-button
              >
              <a-divider direction="vertical" />
              <a-button
                v-if="!record.uploaded && !props.draft"
                type="text"
                @click="showUploadModal(record.id, record.name)"
                >上传附件</a-button
              >
              <span v-if="record.uploaded && !props.draft">
                <a-button
                  type="text"
                  @click="
                    showDownloadModal(
                      record.id,
                      record.name,
                      record.object_name,
                      record.filename
                    )
                  "
                  >下载附件</a-button
                >
                <a-divider direction="vertical" />
                <a-button
                  type="text"
                  status="danger"
                  @click="showRemoveModal(record.id, record.name)"
                  >删除附件</a-button
                >
              </span>
              <a-divider direction="vertical" />
              <a-button
                type="text"
                status="danger"
                @click="confirmRemoveOutcome(rowIndex, record)"
                >删除</a-button
              >
            </div>
            <div v-else class="operate-text-button">
              <a-button type="text" @click="confirmAddOutcome"
                >确认添加</a-button
              >
              <a-divider direction="vertical" />
              <a-button
                type="text"
                status="warning"
                @click="cancelAddOutcome(rowIndex, record)"
                >取消添加</a-button
              >
            </div>
          </template>
          <template #footer>
            <a-button
              type="dashed"
              long
              :disabled="outcomeList.filter(item => item.isCreated).length > 0"
              @click="preAddOutcome"
              ><template #icon><icon-plus /></template>交付物</a-button
            >
          </template>
        </a-table>
      </a-form>
    </div>
    <UploadModal ref="uploadModalRef" />
    <DownloadModal ref="downloadModalRef" />
    <RemoveModal ref="removeModalRef" />
  </a-card>
</template>

<script setup lang="ts">
import {
  addOutcome,
  getOutcomeList,
  modifyOutcome,
  removeOutcome
} from '@/api/project/outcome'
import {
  ChangeMarkerList,
  OutcomeStatusList,
  ComponentsType
} from '@/enums/api'
import { useEmitt } from '@/logics/mitt/useEmitt'
import { Outcome } from '@/types/outcome'
import { TableColumnData, TableData } from '@arco-design/web-vue/es/table'
import { PropType, h, onMounted, reactive, ref, toRaw } from 'vue'
import { format } from 'date-fns'
import { FormInstance, Message, Modal } from '@arco-design/web-vue'
import HoverEditorDetail from '@/components/hover-editor-detail/index.vue'
import UploadModal from './upload.vue'

import DownloadModal from './download.vue'
import RemoveModal from './remove.vue'

const outcomeFormRef = ref<FormInstance>()
const { emitter } = useEmitt()
const uploadModalRef = ref()
const removeModalRef = ref()
const downloadModalRef = ref()
const props = defineProps({
  draft: {
    type: Boolean,
    required: true,
    default: () => {
      return false
    }
  },
  taskId: {
    type: String
  },
  accountList: {
    type: Array as PropType<{ id: string; name: string }[]>,
    required: true
  }
})

const addOutcomeParams = reactive<{
  taskId?: string
  name?: string
  description?: string
  plan_time?: string
}>({
  name: undefined,
  plan_time: undefined,
  description: undefined
})

const tableColumns: TableColumnData[] = [
  {
    title: '序号',
    slotName: 'index',
    width: 150,
    bodyCellClass: (record: TableData) => {
      return getRibbonInfo(record.change_marker)?.subClass || ''
    }
  },
  {
    title: '名称',
    dataIndex: 'name',
    slotName: 'name',
    bodyCellClass: (record: TableData) => {
      return getRibbonInfo(record.change_marker)?.subClass || ''
    }
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    bodyCellClass: (record: TableData) => {
      return getRibbonInfo(record.change_marker)?.subClass || ''
    }
  },
  {
    title: '计划交付时间',
    dataIndex: 'plan_time',
    slotName: 'plan_time',
    bodyCellClass: (record: TableData) => {
      return getRibbonInfo(record.change_marker)?.subClass || ''
    }
  },
  {
    title: '完成交付时间',
    dataIndex: 'completed_at',
    bodyCellClass: (record: TableData) => {
      return getRibbonInfo(record.change_marker)?.subClass || ''
    }
  },

  {
    title: '操作',
    slotName: 'operate',
    width: 280,
    bodyCellClass: (record: TableData) => {
      return getRibbonInfo(record.change_marker)?.subClass || ''
    }
  }
]

const outcomeList = ref<Outcome[]>([])
const getRibbonInfo = (mark: number) => {
  return ChangeMarkerList.find(item => item.value === mark)
}

// 根据交付物状态获取对应样式标签
const outcomeStatus = (status: number) => {
  return OutcomeStatusList.find(item => item.status === status)
}

const getOutcomes = async () => {
  const { list } = await getOutcomeList({
    draft: props.draft,
    task_id: props.taskId!
  })
  outcomeList.value = list
}

/**
 * 跳转到交付物详情
 * @param outcomeId
 */
const redirectOutcomeDetailPage = (outcomeId: string) => {
  emitter.emit('redirectOutcomeDetailPage', outcomeId)
}

// 显示上传交付物
const showUploadModal = (id: string, name: string) => {
  uploadModalRef.value?.showUploadModal(id, name)
}

// 显示下载交付物
const showDownloadModal = (
  id: string,
  name: string,
  objectName: string,
  filename: string
) => {
  downloadModalRef.value?.showDownloadModal(id, name, objectName, filename)
}

/**
 * 删除已上传文件
 * @param objectName 交付物文件id
 * @param name 交付物名称
 */
const showRemoveModal = (objectName: string, name: string) => {
  removeModalRef.value?.showRemoveModal(objectName, name)
}

// 修改信息
const handleModifyOutcomeName = async (
  id: string,
  name: string,
  oldValue: any,
  record: Outcome
) => {
  try {
    await modifyOutcome({ id, name, draft: props.draft })
    Message.success('修改成功')
    if (props.draft) {
      emitter.emit('get_task_list')
    }
  } catch (_e) {
    record.name = oldValue
  }
}

// 修改信息
const handleModifyOutcomePlanTime = async (
  record: Outcome,
  oldValue: string
) => {
  const { id, plan_time: planTime } = record
  try {
    await modifyOutcome({ id, plan_time: planTime, draft: props.draft })
    Message.success('修改成功')
    if (props.draft) {
      emitter.emit('get_task_list')
    }
  } catch (_e) {
    record.plan_time = oldValue
  }
}

// 确认添加交付物
const confirmAddOutcome = async () => {
  const isValid = await outcomeFormRef.value?.validate()
  if (isValid) {
    return
  }
  const { plan_time: planTime, name } = addOutcomeParams
  await addOutcome({
    draft: props.draft,
    name: name!,
    plan_time: planTime!,
    task_id: props.taskId!
  })
  restOutcomeForm()
  getOutcomes()
  Message.success('添加成功')
  if (props.draft) {
    emitter.emit('get_task_list')
  }
}

// 取消添加交付物
const cancelAddOutcome = async (index: number, record: Outcome) => {
  outcomeList.value.splice(index, 1)
  if (record.isCreated) {
    restOutcomeForm()
  }
  // await removeOutcome({ id: record.id, draft: props.draft })
  // Message.success('删除成功')
  // if (props.draft) {
  //   emitter.emit('get_task_list')
  // }
}

// 删除交付物
const confirmRemoveOutcome = async (index: number, record: Outcome) => {
  const title = {
    setup() {
      return () => h('strong', '警告')
    }
  }
  const ModalContent = {
    setup() {
      return () =>
        h('span', { style: 'margin-left: 10px;' }, [
          h('span', `确认删除交付物： `),
          h('strong', `${record.name}`),
          h('span', ` 吗？`)
        ])
    }
  }
  Modal.warning({
    title: () => h(title),
    content: () => h(ModalContent),
    alignCenter: true,
    titleAlign: 'start',
    draggable: true,
    escToClose: true,
    width: 300,
    simple: true,
    hideCancel: false,
    onOk: async () => {
      await removeOutcome({ id: record.id, draft: props.draft })
      outcomeList.value.splice(index, 1)
      Message.success('删除成功')
      if (props.draft) {
        emitter.emit('get_task_list')
      }
    }
  })
}

// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
  name: 'get-outcome-list',
  callback: () => {
    getOutcomes()
  }
})

const restOutcomeForm = async () => {
  outcomeFormRef.value?.resetFields()
}

// 预备添加交付物
const preAddOutcome = () => {
  restOutcomeForm()
  outcomeList.value.push({
    id: '',
    name: '',
    status: 0,
    isCreated: true,
    plan_time: format(new Date(), 'yyyy-MM-dd')
  })
}

onMounted(() => {
  getOutcomes()
})
</script>

<style lang="less" scoped>
.general-card {
  :deep(.arco-card-body) {
    .outcome-table {
      :deep(.query-row-class) {
        .operater {
          .arco-table-cell {
            padding: 0px;
          }
        }
      }
    }
  }
}

:deep(.arco-table-footer) {
  padding: 3px;
}
</style>
