<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { GlobalStore } from '@/stores/index'
import { ref, reactive, nextTick, computed } from 'vue'
import { getFormatDuration } from '@/utils/common'
import { UserFilled } from '@element-plus/icons-vue'
import TableBase from '@/components/TableBase/index.vue'
import { ColumnProps } from '@/components/TableBase/interface/index'
import { User_List } from '@/api/user/index'
import Drawer from '@/components/Drawer/index.vue'
import {
  User_Power_User_list,
  User_Power_Add,
  User_Power_Edit,
  User_Power_Del,
  User_Power_Get
} from '@/api/project/index'
import type { FormInstance, FormRules } from 'element-plus'
import ProjectDetail from './ProjectDetail.vue'
import receiveUser from '@/views/storehouse/outStock/receiveUser.vue'
import { Edit, Delete, View } from '@element-plus/icons-vue'

const isNew = ref(true)
const TableRef = ref()
const disabled = ref(false)
const globalStore = GlobalStore()
const formLabelWidth = ref('120px')
const ruleFormRef = ref<FormInstance>()
const User_tokey = globalStore.GET_User_tokey
const initParam = { User_tokey }
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const receiveUserDrawerRef = ref<InstanceType<typeof receiveUser> | null>(null)
const projectDetailRef = ref<InstanceType<typeof ProjectDetail> | null>(null)

const columns: ColumnProps[] = [
  { prop: 'Id', label: 'ID' },
  { prop: 'T_name', label: '项目名称' },
  { prop: 'T_user_name', label: '项目负责人' },
  { prop: 'T_start_date', label: '立项日期' },
  { prop: 'T_end_date', label: '结束时间' },
  { prop: 'T_planning_cycle', label: '计划完成周期（工作日）' },
  { prop: 'T_name', label: '绩效总金额' },
  { prop: 'T_State', label: '状态' },
  { prop: 'operation', label: '操作', width: 200, fixed: 'right' }
]

const form = ref({
  Id: '',
  T_name: '',
  T_description: '',
  T_detail: '',
  T_planning_cycle: '',
  T_remark: '',
  T_approver: '',
  T_uuid: ''
})

const rules = reactive<FormRules>({
  T_name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }]
})

const openProjectDrawer = (type: string, row?: any) => {
  isNew.value = type === 'new' ? true : false
  nextTick(async () => {
    if (!isNew.value || type === 'view') {
      if (type === 'view') disabled.value = true
      form.value = { ...row }
      form.value.T_approver = row.T_approver_name
      form.value.T_uuid = row.T_approver
      const res: any = await User_Power_Get({ T_id: row.Id })
      if (res.Code === 200) {
        projectDetailRef.value?.setDetailData(res.Data.T_Detail)
      }
    }
  })
  drawerRef.value?.openDrawer()
}
const callbackDrawer = (done: () => void) => {
  resetForm(ruleFormRef.value)
  projectDetailRef.value?.clearDetail()
  isNew.value = true
  disabled.value = false
  done()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const getProjectInfo = ({ T_uuid, T_name }: { T_uuid: string; T_name: string }) => {
  form.value.T_approver = T_name
  form.value.T_uuid = T_uuid
}
const selectApprover = () => receiveUserDrawerRef.value?.openDrawer()
// 计算周期
const getPlanningCycle = (info: any[]) => {
  form.value.T_planning_cycle = info.reduce((cur, pre) => {
    cur = cur + pre.T_planned_time
    return cur
  }, 0)
}

// 提交项目
const addProject = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let res: any = ''
      let detail = ''
      projectDetailRef.value?.getDetailInfo().forEach((item: any) => {
        detail += `${item.T_function},${item.T_planned_time},${item.T_finish}|`
      })
      const params = {
        User_tokey,
        ...form.value,
        T_detail: detail,
        T_approver: form.value.T_uuid
      }
      if (isNew.value) {
        res = await User_Power_Add(params)
      } else {
        res = await User_Power_Edit({ ...params, T_id: form.value.Id })
      }

      if (res.Code === 200) {
        ElMessage.success(`项目${isNew.value ? '添加' : '修改'}成功!`)
        nextTick(() => {
          isNew.value = true
          TableRef.value?.getTableList()
          drawerRef.value?.closeDrawer()
          resetForm(ruleFormRef.value)
        })
      }
    } else return false
  })
}
// 删除
const DeleteProject = (Id: number) => {
  ElMessageBox.confirm('您确定要删除项目吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res: any = await User_Power_Del({ User_tokey, T_id: Id })
      if (res.Code === 200) {
        ElMessage.success('删除成功！')
        nextTick(() => {
          TableRef.value?.getTableList()
        })
      }
    })
    .catch(() => {
      ElMessage.warning('取消成功！')
    })
}
</script>
<template>
  <div class="my-project">
    <TableBase ref="TableRef" :columns="columns" :requestApi="User_Power_User_list" :initParam="initParam">
      <template #table-header>
        <el-row :gutter="20" class="w-100">
          <el-col :span="4" :offset="20"
            ><el-button type="primary" @click="openProjectDrawer('new')">立项申请</el-button></el-col
          >
        </el-row>
      </template>
      <template #right="{ row }">
        <el-button link type="success" size="small" :icon="View" @click="openProjectDrawer('view', row)"
          >详情</el-button
        >
        <el-button link type="primary" size="small" :icon="Edit" @click="openProjectDrawer('edit', row)"
          >编辑</el-button
        >
        <el-button link type="danger" size="small" :icon="Delete" @click="DeleteProject(row.Id)">删除</el-button>
      </template>
    </TableBase>
    <Drawer ref="drawerRef" :handleClose="callbackDrawer" size="50%">
      <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_name">
          <el-input
            v-model="form.T_name"
            :disabled="disabled"
            type="text"
            autocomplete="off"
            placeholder="请输入项目名称"
          />
        </el-form-item>
        <el-form-item label="项目简介：" :label-width="formLabelWidth" prop="T_description">
          <el-input
            v-model="form.T_description"
            :disabled="disabled"
            :autosize="{ minRows: 6, maxRows: 8 }"
            type="textarea"
            placeholder="请输入项目简介"
          />
        </el-form-item>
        <el-form-item label="项目明细：" :label-width="formLabelWidth" prop="T_detail">
          <ProjectDetail ref="projectDetailRef" @onPlanning="getPlanningCycle" :disabled="disabled"></ProjectDetail>
        </el-form-item>
        <el-form-item label="计划完成周期：" :label-width="formLabelWidth" prop="T_planning_cycle">
          <div style="display: flex; white-space: nowrap; flex: 1">
            <el-input
              v-model="form.T_planning_cycle"
              :disabled="disabled"
              type="text"
              autocomplete="off"
              placeholder="请输入计划完成周期"
            />
            <span style="margin: 0 10px">工作日</span>
            <span style="color: #bbb"
              ><el-icon><QuestionFilled /></el-icon>备注;根据项目明细计划时间自动计算</span
            >
          </div>
        </el-form-item>
        <el-form-item label="备注：" :label-width="formLabelWidth" prop="T_remark">
          <el-input
            v-model="form.T_remark"
            :disabled="disabled"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        <el-form-item label="审批人：" :label-width="formLabelWidth" prop="T_approver">
          <el-input
            v-model="form.T_approver"
            :disabled="disabled"
            placeholder="请选择审批人"
            class="w-50"
            @focus="selectApprover"
          />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" v-if="!disabled">
          <el-button v-if="isNew" class="btn" color="#626aef" @click="addProject(ruleFormRef)">提交</el-button>
          <el-button v-else class="btn" color="#626aef" @click="addProject(ruleFormRef)">修改</el-button>
        </el-form-item>
      </el-form>
    </Drawer>
    <receiveUser ref="receiveUserDrawerRef" @onUserInfo="getProjectInfo" title="选择审批人"></receiveUser>
  </div>
</template>

<style scoped lang="scss">
@import '@/styles/var.scss';
:deep(.el-table--enable-row-hover .el-table__body tr) {
  transition: all 0.5s ease-in-out;
}
:deep(.el-table--enable-row-hover .el-table__body tr:hover) {
  box-shadow: 0 0 6px #dfdfdf;
  transform: translateX(-2px);
}
.my-project {
  height: 100%;
  display: flex;
  overflow: hidden;
  @include f-direction;

  :deep(.table-header),
  :deep(.card) {
    margin: 0;
    border-radius: 8px;
  }
  .btn {
    padding: 0 25px;
  }
}
</style>
