<template>
  <vModal
    v-model:visible="visibleModal"
    :title="title"
    hide-cancel
    ok-text="关闭"
    width="950px"
    body-style="padding:10px"
    @modal-handle-ok="modelHandleOk"
    @modal-handle-cancel="modelHandleCancel"
  >
    <div class="container">
      <a-row :gutter="[10, 10]">
        <!-- <a-col :span="24">
          <a-alert banner center>
            <template #icon>
              <icon-link :size="18" />
            </template>
            交付物清单</a-alert
          >
          <a-divider :margin="5" />
          <a-card :bordered="false" class="general-card">
            <a-form
              ref="outcomeFormRef"
              :model="addOutcomeParams"
              :auto-label-width="true"
              label-align="right"
            >
              <a-table
                class="outcome-table"
                :columns="outcomeTableColumns"
                :data="outcomeList"
                :pagination="false"
                table-layout-fixed
                row-class="query-row-class"
                :stripe="false"
                :bordered="{
                  cell: true,
                  headerCell: true,
                  wrapper: true
                }"
                :hoverable="false"
              >
                <template #index="{ rowIndex }">
                  {{ rowIndex + 1 }}
                </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="交付物名称"
                    :components-type="ComponentsType.STRINGINPUT"
                    @modify="handleModifyOutcomeName(record.id, record.name)"
                  />
                </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="计划时间"
                    :components-type="ComponentsType.DATEPICKER"
                    @modify="
                      handleModifyOutcomePlanTime(record.id, record.plan_time)
                    "
                  />
                </template>
                <template #operater="{ record, rowIndex }">
                  <a-space>
                    <a-tooltip content="确认添加交付物">
                      <a-typography-text
                        v-if="record.isCreated"
                        style="cursor: pointer"
                        type="primary"
                      >
                        <icon-check-circle
                          :size="20"
                          @click="confirmAddOutcome"
                        />
                      </a-typography-text>
                    </a-tooltip>
                    <a-tooltip
                      :content="
                        record.isCreated ? '取消添加交付物' : '删除交付物'
                      "
                    >
                      <a-typography-text
                        style="cursor: pointer"
                        type="danger"
                        @click="confirmRemoveOutcome(rowIndex, record)"
                      >
                        <icon-stop v-if="record.isCreated" :size="20" />
                        <icon-minus-circle v-else :size="20" />
                      </a-typography-text>
                    </a-tooltip>
                  </a-space>
                </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>
          </a-card>
        </a-col> -->
        <a-col :span="24">
          <!-- <a-alert banner center type="success">
            <template #icon>
              <icon-font type="my-audit" :size="22" />
            </template>
            审核流程</a-alert
          > -->
          <!-- <a-divider :margin="5" /> -->
          <a-card :bordered="false" class="general-card">
            <!-- <template #title> </template> -->
            <a-form
              ref="auditFormRef"
              :model="addCheckerParams"
              :auto-label-width="true"
              label-align="right"
            >
              <a-table
                class="outcome-table"
                :columns="auditTableColumns"
                :data="checkers"
                table-layout-fixed
                row-class="query-row-class"
                :pagination="false"
                :stripe="false"
                :bordered="{
                  cell: true,
                  headerCell: true,
                  wrapper: true
                }"
                :hoverable="false"
              >
                <template #name="{ record }">
                  <a-form-item
                    v-if="record.isCreated"
                    no-style
                    feedback
                    field="name"
                    :validate-trigger="['change', 'input']"
                    :rules="{
                      required: true
                    }"
                  >
                    <a-select
                      v-model="addCheckerParams.name"
                      placeholder="请选择审核名"
                    >
                      <a-option value="互校" label="互校"></a-option>
                      <a-option value="二审" label="二审"></a-option>
                      <a-option value="终审" label="终审"></a-option>
                    </a-select>
                  </a-form-item>

                  <HoverEditorDetail
                    v-else
                    v-model="record.name"
                    placeholder="审核名"
                    :options="[
                      { id: '互校', name: '互校' },
                      { id: '二审', name: '二审' },
                      { id: '终审', name: '终审' }
                    ]"
                    :components-type="ComponentsType.SELECT"
                    @modify="handleModifyCheckers"
                  />
                </template>
                <template #handlers="{ record }">
                  <a-form-item
                    v-if="record.isCreated"
                    no-style
                    feedback
                    field="handlers"
                    :validate-trigger="['change', 'input']"
                    :rules="{
                      required: true
                    }"
                  >
                    <a-select
                      v-model="addCheckerParams.handlers"
                      :multiple="true"
                      placeholder="请选择审核账号"
                    >
                      <a-option
                        v-for="{ id, name } in accountList"
                        :key="id"
                        :value="id"
                        :label="name"
                      >
                      </a-option>
                    </a-select>
                  </a-form-item>

                  <HoverEditorDetail
                    v-else
                    v-model="record.handlers"
                    placeholder="审核账号"
                    :multiple="true"
                    :options="accountList"
                    :components-type="ComponentsType.SELECT"
                    @modify="handleModifyCheckers"
                  />
                </template>
                <template #due_day="{ record }">
                  <a-form-item
                    v-if="record.isCreated"
                    no-style
                    feedback
                    field="due_day"
                    :validate-trigger="['change', 'input']"
                    :rules="{
                      required: true
                    }"
                  >
                    <a-input-number
                      v-model="addCheckerParams.due_day"
                      placeholder="请输入超时时限"
                      :min="1"
                    />
                  </a-form-item>

                  <HoverEditorDetail
                    v-else
                    v-model="record.due_day"
                    placeholder="超时时限"
                    :components-type="ComponentsType.NUMBERINPUT"
                    @modify="handleModifyCheckers"
                  />
                </template>
                <template #footer>
                  <a-button
                    type="dashed"
                    long
                    :disabled="
                      checkers.filter(item => item.isCreated).length > 0
                    "
                    @click="preAddChecker"
                    ><template #icon><icon-plus /></template>审核</a-button
                  >
                </template>
                <template #operater="{ record, rowIndex }">
                  <div v-if="record.isCreated" class="operate-text-button">
                    <a-button type="text" @click="confirmAddChecker"
                      >确认添加</a-button
                    >
                    <a-divider direction="vertical" />
                    <a-button
                      type="text"
                      status="warning"
                      @click="confirmRemoveChecker(rowIndex, record)"
                      >取消添加</a-button
                    >
                  </div>
                  <div v-else>
                    <a-button
                      type="text"
                      status="danger"
                      @click="confirmRemoveChecker(rowIndex, record)"
                      >删除</a-button
                    >
                  </div>
                  <!-- <a-space>
                    <a-tooltip content="确认添加审核">
                      <a-typography-text
                        v-if="record.isCreated"
                        style="cursor: pointer"
                        type="primary"
                      >
                        <icon-check-circle
                          :size="20"
                          @click="confirmAddChecker"
                        />
                      </a-typography-text>
                    </a-tooltip>
                    <a-tooltip
                      :content="record.isCreated ? '取消添加审核' : '删除审核'"
                    >
                      <a-typography-text
                        style="cursor: pointer"
                        type="danger"
                        @click="confirmRemoveChecker(rowIndex, record)"
                      >
                        <icon-stop v-if="record.isCreated" :size="20" />
                        <icon-minus-circle v-else :size="20" />
                      </a-typography-text>
                    </a-tooltip>
                  </a-space> -->
                </template>
              </a-table>
            </a-form>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </vModal>
</template>

<script setup lang="ts">
import { PropType, reactive, ref } from 'vue'
import {
  FormInstance,
  Icon,
  Message,
  TableColumnData
} from '@arco-design/web-vue'
// import { Outcome } from '@/types/outcome'
import { ComponentsType, IconFontUrl } from '@/enums/api'
import HoverEditorDetail from '@/components/hover-editor-detail/index.vue'
import vModal from '@/components/modal/index.vue'
// import {
//   addOutcome,
//   getOutcomeList,
//   modifyOutcome,
//   removeOutcome
// } from '@/api/project/outcome'
import { getPlanCheckFlow, setPlanCheckFlow } from '@/api/project/plan-task'
// import { format } from 'date-fns'
import { useEmitt } from '@/logics/mitt/useEmitt'
import { Checker } from '@/types/plan-task'

const props = defineProps({
  draft: {
    type: Boolean,
    required: true,
    default: () => {
      return false
    }
  },
  accountList: {
    type: Array as PropType<{ id: string; name: string }[]>
  }
})
const IconFont = Icon.addFromIconFontCn({
  src: IconFontUrl.URL
})
const title = ref('设置审核流程')
const visibleModal = ref(false)
// const outcomeFormRef = ref<FormInstance>()
const auditFormRef = ref<FormInstance>()
// const outcomeTableColumns: TableColumnData[] = [
//   {
//     title: '名称',
//     dataIndex: 'name',
//     slotName: 'name',
//     width: 250
//   },
//   {
//     title: '计划交付时间',
//     dataIndex: 'plan_time',
//     slotName: 'plan_time',
//     width: 250
//   },
//   {
//     title: '完成交付时间',
//     dataIndex: 'completed_at',
//     slotName: 'completed_at',
//     width: 150
//   },
//   {
//     title: '操作',
//     slotName: 'operater',
//     bodyCellClass: 'operater',
//     align: 'center',
//     fixed: 'right',
//     width: 100
//   }
// ]
const auditTableColumns: TableColumnData[] = [
  {
    title: '审核名称',
    dataIndex: 'name',
    slotName: 'name',
    width: 250
  },
  {
    title: '审核账号',
    dataIndex: 'handlers',
    slotName: 'handlers',
    width: 250
  },
  {
    title: '超时时限（天）',
    dataIndex: 'due_day',
    slotName: 'due_day',
    width: 150
  },
  {
    title: '操作',
    slotName: 'operater',
    bodyCellClass: 'operater',
    align: 'center',
    fixed: 'right',
    width: 180
  }
]

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

const addCheckerParams = reactive<{
  taskId?: string
  name?: string // 页码
  handlers?: string[] // 审核人账号id 审核人账号名称
  due_day?: number // 超时时限（天）超时后产生提醒
}>({
  name: undefined,
  handlers: undefined,
  due_day: 3
})

const { emitter } = useEmitt()

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

const restCheckerForm = async () => {
  addCheckerParams.name = undefined
  addCheckerParams.handlers = undefined
  addCheckerParams.due_day = undefined
}

// const outcomeList = ref<Outcome[]>([])
const checkers = ref<Checker[]>([])

// const getList = async (id: string) => {
//   addOutcomeParams.taskId = id
//   const { list } = await getOutcomeList({ task_id: id, draft: props.draft })
//   outcomeList.value = list
// }

const getCheckers = async (id: string) => {
  addCheckerParams.taskId = id
  const { checkers: list } = await getPlanCheckFlow({
    task_id: id,
    draft: props.draft
  })
  checkers.value = list
}
/**
 * 显modal
 * @param taskId 任务编号
 */
const showSetOutcomePage = async (id: string, name: string) => {
  title.value = `${name}-审核流程`
  // await getList(id)
  visibleModal.value = true
  await getCheckers(id)
}

/**
 * 隐藏model 对话框，重置表单
 */
const modelHandleCancel = () => {
  // outcomeList.value = []
  checkers.value = []
  // restOutcomeForm()
  restCheckerForm()
}
/**
 * 点击确认按钮时，cb(false)时不会继续后续操作
 * @param cb 回调函数，
 */
const modelHandleOk = async (cb: (closed: boolean) => void) => {
  // outcomeList.value = []
  // await restOutcomeForm()
  // addOutcomeParams.
  return cb(true)
}

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

// 预备添加审核流程
const preAddChecker = () => {
  checkers.value.push({
    name: '互校',
    isCreated: true,
    handlers: [],
    due_day: 3
  })
}

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

// 确认添加交付物
const confirmAddChecker = async () => {
  const isValid = await auditFormRef.value?.validate()
  if (isValid) {
    return
  }
  const { taskId, name, handlers, due_day: dueDay } = addCheckerParams
  checkers.value.push({
    name: name!,
    handlers: handlers!,
    due_day: dueDay!
  })
  checkers.value = checkers.value.filter(item => !item.isCreated)
  await setPlanCheckFlow({
    draft: props.draft,
    task_id: addCheckerParams.taskId!,
    checkers: checkers.value
  })
  restCheckerForm()
  Message.success('添加成功')
  await getCheckers(taskId!)
}

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

// 删除审核
const confirmRemoveChecker = async (index: number, record: Checker) => {
  checkers.value.splice(index, 1)
  if (record.isCreated) {
    restCheckerForm()
    return
  }
  checkers.value = checkers.value.filter(item => !item.isCreated)
  await setPlanCheckFlow({
    draft: props.draft,
    task_id: addCheckerParams.taskId!,
    checkers: checkers.value
  })
  Message.success('删除成功')
  restCheckerForm()
  if (props.draft) {
    emitter.emit('get_task_list')
  }
}

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

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

const handleModifyCheckers = async () => {
  checkers.value = checkers.value.filter(item => !item.isCreated)
  Message.success('修改成功')
  await setPlanCheckFlow({
    draft: props.draft,
    task_id: addCheckerParams.taskId!,
    checkers: checkers.value
  })
  if (props.draft) {
    emitter.emit('get_task_list')
  }
}

defineExpose({ showSetOutcomePage }) // 暴露子组件的方法或者数据
</script>

<script lang="ts">
export default {
  name: 'SetOutsome'
}
</script>

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