<template>
  <a-card class="checkers-card" title="审核流程" style="margin-top: 8px">
    <div class="item-container">
      <a-form
        ref="auditFormRef"
        :model="addCheckerParams"
        :auto-label-width="true"
        label-align="right"
      >
        <a-table
          style="padding: 0 16px"
          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: '终审' }
              ]"
              :old-value="toRaw(record.name)"
              :components-type="ComponentsType.SELECT"
              @modify="oldValue => handleModifyNameCheckers(record, oldValue)"
            />
          </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"
              :not-allow-null="true"
              :old-value="toRaw(record.handlers)"
              :options="accountList"
              :components-type="ComponentsType.SELECT"
              @modify="
                oldValue => handleModifyHandlersCheckers(record, oldValue)
              "
            />
          </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="超时时限"
              :not-allow-null="true"
              :old-value="toRaw(record.due_day)"
              :components-type="ComponentsType.NUMBERINPUT"
              @modify="oldValue => handleModifyDueDayCheckers(record, oldValue)"
            />
          </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>
    </div>
  </a-card>
  <!-- </a-row> -->
  <!-- </div> -->
  <!-- </vModal> -->
</template>

<script setup lang="ts">
import { PropType, onMounted, reactive, ref, toRaw } 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
    }
  },
  taskId: {
    type: String
  },
  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 = 1
}

// 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) => {
  if (id) {
    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 confirmAddChecker = async () => {
  const isValid = await auditFormRef.value?.validate()
  if (isValid) {
    return
  }
  const { taskId, name, handlers, due_day: dueDay } = addCheckerParams
  try {
    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('添加成功')
    emitter.emit('get_task_list')
    emitter.emit('get_task_detail')
  } catch (_e) {
    getCheckers(taskId!)
  }
}
// 删除审核
const confirmRemoveChecker = async (index: number, record: Checker) => {
  try {
    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()
    emitter.emit('get_task_list')
    emitter.emit('get_task_detail')
  } catch (e) {
    getCheckers(addCheckerParams.taskId!)
  }
}

// 修改信息
// 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 handleModifyNameCheckers = async (record: Checker, oldValue: string) => {
  try {
    checkers.value = checkers.value.filter(item => !item.isCreated)
    await setPlanCheckFlow({
      draft: props.draft,
      task_id: addCheckerParams.taskId!,
      checkers: checkers.value
    })
    Message.success('修改成功')
    emitter.emit('get_task_list')
    emitter.emit('get_task_detail')
  } catch (_e) {
    record.name = oldValue
  }
}

const handleModifyHandlersCheckers = async (
  record: Checker,
  oldValue: string[]
) => {
  try {
    checkers.value = checkers.value.filter(item => !item.isCreated)
    await setPlanCheckFlow({
      draft: props.draft,
      task_id: addCheckerParams.taskId!,
      checkers: checkers.value
    })
    Message.success('修改成功')
    emitter.emit('get_task_list')
    emitter.emit('get_task_detail')
  } catch (_e) {
    record.handlers = oldValue
  }
}

const handleModifyDueDayCheckers = async (
  record: Checker,
  oldValue: number
) => {
  try {
    checkers.value = checkers.value.filter(item => !item.isCreated)
    await setPlanCheckFlow({
      draft: props.draft,
      task_id: addCheckerParams.taskId!,
      checkers: checkers.value
    })
    Message.success('修改成功')
    // if (props.draft) {
    emitter.emit('get_task_list')
    emitter.emit('get_task_detail')
    // }
  } catch (_e) {
    record.due_day = oldValue
  }
}

// defineExpose({ showSetOutcomePage }) // 暴露子组件的方法或者数据
onMounted(() => {
  getCheckers(props.taskId)
})
</script>

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

<style lang="less" scoped>
.checkers-card {
  :deep(.arco-card-header) {
    height: auto;
    padding: 20px;
    border-bottom: none;
  }

  :deep(.arco-card-body) {
    padding: 0 20px 20px 20px;

    .outcome-table {
      :deep(.query-row-class) {
        .operater {
          .arco-table-cell {
            padding: 0px;
          }
        }
      }
    }
  }
}

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