<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, reactive, nextTick } from 'vue'
import { GlobalStore } from '@/stores/index'
import ProjectDetail from './ProjectDetail.vue'
import Drawer from '@/components/Drawer/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Project_Get, Project_Edit, Project_Add } from '@/api/project/index'
import receiveUser from '@/views/storehouse/outStock/receiveUser.vue'

const typeTip = ref('')
const formLabelWidth = ref('120px')
const globalStore = GlobalStore()
const User_tokey = globalStore.GET_User_tokey
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const projectDetailRef = ref<InstanceType<typeof ProjectDetail> | null>(null)
const receiveUserDrawerRef = ref<InstanceType<typeof receiveUser> | null>(null)
const form = ref({
  Id: '',
  T_name: '',
  T_end_date: '',
  T_set_up_date: '',
  T_description: '',
  T_detail: '',
  T_planning_cycle: '',
  T_reality_cycle: '',
  T_bonus: '',
  T_Perf: '',
  T_remark: '',
  T_approver: '',
  T_advance_day: '',
  T_uuid: ''
})
const rules = reactive<FormRules>({
  T_name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }]
})
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const callbackDrawer = (done: () => void) => {
  resetForm(ruleFormRef.value)
  projectDetailRef.value?.clearDetail()
  done()
}
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 (typeTip.value === 'new') {
        res = await Project_Add(params)
      } else {
        res = await Project_Edit({ ...params, T_id: form.value.Id })
      }

      if (res.Code === 200) {
        ElMessage.success(`项目${typeTip.value === 'new' ? '添加' : '修改'}成功!`)
        nextTick(() => {
          emit('onTableList')
          drawerRef.value?.closeDrawer()
          resetForm(ruleFormRef.value)
        })
      }
    }
  })
}

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 + Number(pre.T_planned_time)
    return cur
  }, 0)
}

const projectFromOpen = (type: string, row?: any) => {
  typeTip.value = type
  nextTick(async () => {
    if (typeTip.value !== 'new') {
      form.value = { ...row }
      form.value.T_approver = row.T_approver_name
      form.value.T_uuid = row.T_approver
      const res: any = await Project_Get({ T_id: row.Id })
      if (res.Code === 200) {
        projectDetailRef.value?.setDetailData(res.Data.T_Detail)
      }
    }
  })
  drawerRef.value?.openDrawer()
}

const props = defineProps<{ projectName: string }>()
const projectName = ref(props.projectName)

const getTitle = (type: string) => {
  switch (type) {
    case 'new':
      return '新增'
    case 'edit':
      return '编辑'
    default:
      return '详情'
  }
}

const emit = defineEmits<{ (event: 'onTableList'): void }>()

defineExpose({
  projectFromOpen
})
</script>
<template>
  <Drawer ref="drawerRef" :handleClose="callbackDrawer" size="50%">
    <template #header="{ params }">
      <h4 :id="params.titleId" :class="params.titleClass">项目 - {{ getTitle(typeTip) }}</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"
          class="w-50"
          :disabled="!(projectName === 'myProject' && (typeTip === 'new' || typeTip === 'edit'))"
          type="text"
          autocomplete="off"
          placeholder="请输入项目名称"
        />
      </el-form-item>
      <el-form-item label="项目结束日期：" :label-width="formLabelWidth" prop="T_end_date">
        <el-date-picker
          style="flex: 0 0 50%"
          class="my-date-picker"
          v-model="form.T_end_date"
          :disabled="!(projectName === 'project' && typeTip === 'edit')"
          type="date"
          placeholder="项目结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="项目立项日期：" :label-width="formLabelWidth" prop="T_set_up_date">
        <el-date-picker
          style="flex: 0 0 50%"
          class="my-date-picker"
          v-model="form.T_set_up_date"
          :disabled="!(projectName === 'project' && typeTip === 'edit')"
          type="date"
          placeholder="项目立项日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="项目简介：" :label-width="formLabelWidth" prop="T_description">
        <el-input
          v-model="form.T_description"
          :disabled="!(projectName === 'myProject' && (typeTip === 'new' || typeTip === 'edit'))"
          :autosize="{ minRows: 6, maxRows: 8 }"
          type="textarea"
          placeholder="请输入项目简介"
        />
      </el-form-item>
      <el-form-item label="项目明细：" :label-width="formLabelWidth" prop="T_detail">
        <ProjectDetail
          ref="projectDetailRef"
          :disabled="!(projectName === 'myProject' && (typeTip === 'new' || typeTip === 'edit'))"
          :isShow="projectName"
          @onPlanning="getPlanningCycle"
        ></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"
            style="flex: 0 0 33.33%"
            :disabled="true"
            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>
      <!-- my project -->
      <el-form-item :label-width="formLabelWidth" prop="T_remark">
        <el-input
          v-model="form.T_remark"
          :disabled="!(projectName === 'myProject' && (typeTip === 'new' || typeTip === 'edit'))"
          :autosize="{ minRows: 4, maxRows: 6 }"
          type="textarea"
          placeholder="请输入备注信息"
        />
      </el-form-item>
      <el-form-item v-if="projectName === 'myProject'" label="审批人：" :label-width="formLabelWidth" prop="T_approver">
        <el-input
          v-model="form.T_approver"
          :disabled="typeTip === 'view'"
          placeholder="请选择审批人"
          class="w-50"
          @focus="selectApprover"
        />
      </el-form-item>
      <!-- my project -->
      <el-form-item label="实际完成周期：" :label-width="formLabelWidth" prop="T_reality_cycle">
        <div style="display: flex; white-space: nowrap; flex: 1">
          <el-input
            v-model="form.T_reality_cycle"
            class="w-50"
            :disabled="!(projectName === 'project' && typeTip === 'edit')"
            type="text"
            autocomplete="off"
            placeholder="请输入实际完成周期"
          />
          <span style="margin: 0 10px">工作日</span>
        </div>
      </el-form-item>
      <el-form-item label="提前完成天数：" :label-width="formLabelWidth" prop="T_advance_day">
        <div style="display: flex; white-space: nowrap; flex: 1">
          <el-input
            v-model="form.T_advance_day"
            class="w-50"
            :disabled="!(projectName === 'project' && typeTip === 'edit')"
            type="text"
            autocomplete="off"
            placeholder="请输入提前完成天数"
          />
          <span style="margin: 0 10px">工作日</span>
        </div>
      </el-form-item>
      <el-form-item label="奖励金额：" :label-width="formLabelWidth" prop="T_bonus">
        <div style="display: flex; white-space: nowrap; flex: 1">
          <el-input
            v-model="form.T_bonus"
            class="w-50"
            :disabled="!(projectName === 'project' && typeTip === 'edit')"
            type="text"
            autocomplete="off"
            placeholder="请输入奖励金额"
          />
          <span style="margin: 0 10px">元</span>
        </div>
      </el-form-item>
      <el-form-item label="绩效总金额：" :label-width="formLabelWidth" prop="T_Perf">
        <div style="display: flex; white-space: nowrap; flex: 1">
          <el-input
            v-model="form.T_Perf"
            class="w-50"
            :disabled="!(projectName === 'project' && typeTip === 'edit')"
            type="text"
            autocomplete="off"
            placeholder="请输入绩效总金额"
          />
          <span style="margin: 0 10px">元</span>
        </div>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" v-if="projectName === 'project' || projectName === 'myProject'">
        <el-button v-if="typeTip === 'new'" class="btn" color="#626aef" @click="addProject(ruleFormRef)"
          >提交</el-button
        >
        <el-button v-if="typeTip === 'edit'" class="btn" color="#626aef" @click="addProject(ruleFormRef)"
          >修改</el-button
        >
      </el-form-item>
    </el-form>
    <receiveUser
      ref="receiveUserDrawerRef"
      :dept_leader="1"
      @onUserInfo="getProjectInfo"
      title="选择审批人"
    ></receiveUser>
  </Drawer>
</template>
<style scoped lang="scss">
.btn {
  padding: 0 25px;
}
.w-50 {
  flex: 0 0 50%;
}
</style>
