<script setup lang="ts">
import { ref, reactive, nextTick, computed } from 'vue'
import Drawer from '@/components/Drawer/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ColumnProps } from '@/components/TableBase/interface/index'
import { generateRandom } from '@/utils/common'

const isNew = ref(true)
const tableData = ref<any[]>([])
const formLabelWidth = ref('140px')
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)

const form = ref({
  id: '',
  T_function: '',
  T_planned_time: '',
  T_finish: ''
})
const rules = reactive<FormRules>({
  T_function: [{ required: true, message: '请输入功能与指标', trigger: 'blur' }],
  T_planned_time: [{ required: true, message: '请输入计划时间(工作日)', trigger: 'blur' }]
})
const columns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80, align: 'center' },
  { prop: 'T_function', label: '功能与指标', align: 'center' },
  { prop: 'T_planned_time', label: '计划时间(工作日)', align: 'center', width: 160 },
  { prop: 'T_finish', label: '是否完成(原因)', align: 'center', width: 140 },
  { prop: 'operation', label: '操作', width: 160, fixed: 'right', align: 'center' }
]

const openProductionDetailed = (type: string, row?: any) => {
  isNew.value = type === 'new' ? true : false
  if (!isNew.value) {
    form.value = { ...row }
  }
  drawerRef.value?.openDrawer()
}
const callbackDrawer = (done: () => void) => {
  done()
  resetForm(ruleFormRef.value)
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const deleteProjectDetail = (id: string) => {
  tableData.value = tableData.value.filter((item: any) => item.id !== id)
  emit('onPlanning', tableData.value)
}
const addProjectDetail = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      if (isNew.value) {
        tableData.value.push({ ...form.value, id: generateRandom() })
      } else {
        const index = tableData.value.findIndex(item => item.id === form.value.id)
        tableData.value[index] = { ...form.value }
      }
      emit('onPlanning', tableData.value)
      nextTick(() => {
        isNew.value = true
        drawerRef.value?.closeDrawer()
        resetForm(ruleFormRef.value)
      })
    } else return false
  })
}
const emit = defineEmits<{ (event: 'onPlanning', value: any): void }>()
const getDetailInfo = () => tableData.value
const clearDetail = () => (tableData.value = [])
const setDetailData = (info: any[]) => {
  tableData.value = info.map((item: any) => {
    item.id = generateRandom()
    return item
  })
}
defineExpose({
  getDetailInfo,
  clearDetail,
  setDetailData
})
const props = defineProps<{ disabled: boolean; isShow?: string }>()
const disabled = computed(() => props.disabled)
const isShow = ref(props.isShow)
</script>

<template>
  <el-table
    stripe
    :data="tableData"
    style="width: 100%"
    :header-cell-style="{
      background: 'rgb(225 226 228)',
      color: '#000'
    }"
  >
    <template v-for="item in columns" :key="item.prop">
      <el-table-column show-overflow-tooltip v-bind="item" v-if="item.type === 'index'"></el-table-column>
      <el-table-column show-overflow-tooltip v-bind="item" v-if="item.fixed !== 'right' && item.type !== 'index'"> </el-table-column>
      <el-table-column show-overflow-tooltip v-bind="item" v-if="item.fixed === 'right' && isShow === 'myProject'">
        <template #default="{ row }">
          <el-button size="small" :disabled="disabled" type="primary" @click="openProductionDetailed('edit', row)"
            >编辑</el-button
          >
          <el-button size="small" :disabled="disabled" type="danger" @click="deleteProjectDetail(row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </template>
    <template #append v-if="isShow === 'myProject'">
      <el-button type="primary" :disabled="disabled" @click="openProductionDetailed('new')">
        <el-icon><Plus /></el-icon><span style="margin-left: 6px">添加</span>
      </el-button>
    </template>
  </el-table>
  <Drawer ref="drawerRef" :handleClose="callbackDrawer">
    <template #header="{ params }">
      <h4 :id="params.titleId" :class="params.titleClass">{{ isNew ? '添加' : '编辑' }} - 项目明细</h4>
    </template>
    <el-form ref="ruleFormRef" :model="form" :rules="rules">
      <el-form-item label="功能与指标：" :label-width="formLabelWidth" prop="T_function">
        <el-input v-model="form.T_function" type="text" autocomplete="off" placeholder="请输入功能与指标" />
      </el-form-item>
      <el-form-item label="计划时间：" :label-width="formLabelWidth" prop="T_planned_time">
        <el-input v-model="form.T_planned_time" type="text" autocomplete="off" placeholder="请输入计划时间" />
      </el-form-item>
      <el-form-item label="是否完成(原因)：" :label-width="formLabelWidth" prop="T_finish">
        <el-input v-model="form.T_finish" type="text" autocomplete="off" placeholder="请输入完成与否(原因)" />
      </el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <el-button v-if="isNew" class="btn" :disabled="disabled" type="primary" @click="addProjectDetail(ruleFormRef)"
          >添加</el-button
        >
        <el-button v-else class="btn" :disabled="disabled" type="primary" @click="addProjectDetail(ruleFormRef)"
          >修改</el-button
        >
      </el-form-item>
    </el-form>
  </Drawer>
</template>

<style scoped lang="scss">
:deep(.el-drawer__body .el-table .cell) {
  white-space: normal !important;
}
.el-form-item {
  margin-bottom: 18px;
}
</style>
