<script setup lang="ts">
import { computed, nextTick, reactive, watch } from 'vue';
import { RDMS_OBJECT_DIRECTION_DICT_CODE, RDMS_PROJECT_TYPE_DICT_CODE } from '@/constants/dict';
import { useDict } from '@/hooks/business/dict';
import { useForm, useFormRules } from '@/hooks/common/form';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import BusinessFormSection from '@/components/custom/business-form-section.vue';
import DictSelect from '@/components/custom/dict-select.vue';
import { getProjectBaseInfoReadonlyMessage, isProjectBaseInfoEditable } from '../shared';

defineOptions({ name: 'ProjectBaseInfoDialog' });

interface Props {
  baseInfo: Api.Project.ProjectSettingBaseInfo | null;
}

interface Emits {
  (e: 'submit', payload: Api.Project.UpdateProjectSettingBaseInfoParams): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { getLabel: getDirectionLabel } = useDict(RDMS_OBJECT_DIRECTION_DICT_CODE);
const { getLabel: getProjectTypeLabel } = useDict(RDMS_PROJECT_TYPE_DICT_CODE);
const { formRef, validate } = useForm();
const { createRequiredRule } = useFormRules();

const model = reactive<Api.Project.UpdateProjectSettingBaseInfoParams>({
  projectName: '',
  directionCode: '',
  projectType: '',
  plannedStartDate: null,
  plannedEndDate: null,
  projectDesc: null
});

const baseInfoEditable = computed(() => isProjectBaseInfoEditable(props.baseInfo?.statusCode));
const hasAssociatedProduct = computed(() => Boolean(props.baseInfo?.productId));
const directionReadonly = computed(() => baseInfoEditable.value && hasAssociatedProduct.value);
const readonlyMessage = computed(() => getProjectBaseInfoReadonlyMessage(props.baseInfo?.statusCode));
const confirmDisabled = computed(() => !props.baseInfo || !baseInfoEditable.value);

const directionDisplayName = computed(() => {
  const directionCode = props.baseInfo?.directionCode;

  if (!directionCode) {
    return '';
  }

  return getDirectionLabel(directionCode, directionCode);
});

const projectTypeDisplayName = computed(() => {
  const projectType = props.baseInfo?.projectType;

  if (!projectType) {
    return '';
  }

  return getProjectTypeLabel(projectType, projectType);
});

const rules = {
  projectName: [createRequiredRule('请输入项目名称')],
  directionCode: [createRequiredRule('请选择项目方向')],
  projectType: [createRequiredRule('请选择项目类型')]
} satisfies Record<string, App.Global.FormRule[]>;

async function handleConfirm() {
  if (confirmDisabled.value) {
    return;
  }

  await validate();

  emit('submit', {
    projectName: model.projectName.trim(),
    directionCode: directionReadonly.value ? props.baseInfo?.directionCode || model.directionCode : model.directionCode,
    projectType: model.projectType,
    plannedStartDate: model.plannedStartDate,
    plannedEndDate: model.plannedEndDate,
    projectDesc: model.projectDesc?.trim() || null
  });
}

watch(
  () => visible.value,
  async value => {
    if (!value || !props.baseInfo) {
      return;
    }

    model.projectName = props.baseInfo.projectName || '';
    model.directionCode = props.baseInfo.directionCode || '';
    model.projectType = props.baseInfo.projectType || '';
    model.plannedStartDate = props.baseInfo.plannedStartDate;
    model.plannedEndDate = props.baseInfo.plannedEndDate;
    model.projectDesc = props.baseInfo.projectDesc || '';

    await nextTick();
    formRef.value?.clearValidate();
  }
);
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    title="编辑基础信息"
    preset="md"
    :confirm-disabled="confirmDisabled"
    @confirm="handleConfirm"
  >
    <ElAlert v-if="readonlyMessage" :title="readonlyMessage" type="warning" :closable="false" class="mb-16px" />

    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <BusinessFormSection title="项目信息">
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="项目编码">
              <ElInput :model-value="baseInfo?.projectCode || ''" readonly class="base-info-dialog__readonly-input" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="项目名称" prop="projectName">
              <ElInput
                v-if="baseInfoEditable"
                v-model="model.projectName"
                maxlength="200"
                placeholder="请输入项目名称"
              />
              <ElInput
                v-else
                :model-value="model.projectName"
                readonly
                class="base-info-dialog__readonly-input"
                placeholder="未获取到项目名称"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="项目方向" prop="directionCode">
              <DictSelect
                v-if="baseInfoEditable && !directionReadonly"
                v-model="model.directionCode"
                :dict-code="RDMS_OBJECT_DIRECTION_DICT_CODE"
                filterable
                placeholder="请选择项目方向"
              />
              <ElInput
                v-else
                :model-value="directionDisplayName"
                readonly
                class="base-info-dialog__readonly-input"
                placeholder="未获取到项目方向"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="项目类型" prop="projectType">
              <DictSelect
                v-if="baseInfoEditable"
                v-model="model.projectType"
                :dict-code="RDMS_PROJECT_TYPE_DICT_CODE"
                filterable
                placeholder="请选择项目类型"
              />
              <ElInput
                v-else
                :model-value="projectTypeDisplayName"
                readonly
                class="base-info-dialog__readonly-input"
                placeholder="未获取到项目类型"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="所属产品">
              <ElInput
                :model-value="baseInfo?.productName || baseInfo?.productId || '未关联产品'"
                readonly
                class="base-info-dialog__readonly-input"
                placeholder="未关联产品"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem>
              <template #label>
                <span class="business-form-label-with-tip">
                  <ElTooltip
                    content="如需调整项目经理，请到项目内的团队管理处处理。"
                    popper-class="business-form-label-tooltip"
                    placement="top-start"
                  >
                    <span class="business-form-label-tip">
                      <icon-fe:question />
                    </span>
                  </ElTooltip>
                  <span>项目经理</span>
                </span>
              </template>
              <ElInput
                :model-value="baseInfo?.managerUserNickname || baseInfo?.managerUserId || ''"
                readonly
                class="base-info-dialog__readonly-input"
                placeholder="未获取到项目经理"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="计划开始日期">
              <ElDatePicker
                v-if="baseInfoEditable"
                v-model="model.plannedStartDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择计划开始日期"
                class="base-info-dialog__date-picker"
              />
              <ElInput
                v-else
                :model-value="model.plannedStartDate || ''"
                readonly
                class="base-info-dialog__readonly-input"
                placeholder="未填写计划开始日期"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="计划结束日期">
              <ElDatePicker
                v-if="baseInfoEditable"
                v-model="model.plannedEndDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择计划结束日期"
                class="base-info-dialog__date-picker"
              />
              <ElInput
                v-else
                :model-value="model.plannedEndDate || ''"
                readonly
                class="base-info-dialog__readonly-input"
                placeholder="未填写计划结束日期"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="24">
            <ElFormItem label="项目说明">
              <ElInput
                v-if="baseInfoEditable"
                v-model="model.projectDesc"
                type="textarea"
                :rows="4"
                maxlength="4000"
                show-word-limit
                placeholder="请输入项目说明"
              />
              <ElInput
                v-else
                :model-value="model.projectDesc || ''"
                type="textarea"
                :rows="4"
                readonly
                class="base-info-dialog__readonly-input"
                placeholder="未填写项目说明"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </BusinessFormSection>
    </ElForm>
  </BusinessFormDialog>
</template>

<style scoped>
:deep(.base-info-dialog__readonly-input .el-input__wrapper) {
  background: linear-gradient(180deg, rgb(241 245 249 / 98%), rgb(226 232 240 / 94%)), rgb(241 245 249);
  box-shadow: 0 0 0 1px rgb(203 213 225 / 96%) inset;
  cursor: default;
}

:deep(.base-info-dialog__readonly-input .el-textarea__inner) {
  background: linear-gradient(180deg, rgb(241 245 249 / 98%), rgb(226 232 240 / 94%)), rgb(241 245 249);
  box-shadow: 0 0 0 1px rgb(203 213 225 / 96%) inset;
  cursor: default;
  resize: none;
}

:deep(.base-info-dialog__readonly-input .el-input__wrapper:hover),
:deep(.base-info-dialog__readonly-input.is-focus .el-input__wrapper),
:deep(.base-info-dialog__readonly-input .el-textarea__inner:hover),
:deep(.base-info-dialog__readonly-input .el-textarea__inner:focus) {
  box-shadow: 0 0 0 1px rgb(203 213 225 / 96%) inset;
}

:deep(.base-info-dialog__readonly-input .el-input__inner),
:deep(.base-info-dialog__readonly-input .el-textarea__inner) {
  color: rgb(51 65 85 / 96%);
  cursor: default;
  -webkit-text-fill-color: rgb(51 65 85 / 96%);
}

:deep(.base-info-dialog__date-picker.el-date-editor.el-input) {
  width: 100%;
}
</style>
