<template>
  <div class="project-info">
    <template
      v-if="['/personal_workbench/project', '/project_manage/book', '/project_manage/project'].includes(backPath)"
    >
      <MenuPage :cur-key="backPath" />
    </template>
    <template v-if="['org/book', 'org/final', 'org/project'].includes(backPath)">
      <ProjectMenu :cur-key="backPath" />
    </template>

    <div class="project-info__header">
      <div class="menu-container">
        <span class="name">{{ project.name }}</span>
      </div>
      <div class="courseware">
        <span class="name-path"></span>
        <div class="operator">
          <span class="link" @click="$router.push({ path: backPath })">返回项目列表</span>
        </div>
      </div>
    </div>

    <main class="project-info-manage">
      <div class="table-fourcolumn">
        <span class="label">项目名称</span>
        <div class="project-item">
          <span>{{ project.name }}</span>
          <span v-if="isManage" class="link" @click="showUpdateField('name', project.name)">更改</span>
        </div>
        <span class="label">项目分类</span>
        <div class="project-item">
          <span>{{ project.category }}</span>
          <span v-if="isManage" class="link" @click="showUpdateField('category', project.category)">更改</span>
        </div>

        <span class="label" style="line-height: 290px">教材封面</span>
        <div class="project-item">
          <div v-if="project.cover_image_file_url?.length > 0" class="cover-image">
            <img :src="project.cover_image_file_url" alt="cover image" />
          </div>
          <div v-else></div>
          <span
            v-if="isManage"
            class="link"
            @click="showUpdateField('cover_image_file_url', project.cover_image_file_url)"
            >更改</span
          >
        </div>

        <div class="label label-list">
          <span>语种</span>
          <span>出版单位</span>
          <span>作品标签</span>
          <span>所属课题</span>
          <span>作者</span>
        </div>
        <div class="project-item info-list">
          <div class="info-item">
            <span>{{ project.language }}</span>
            <span v-if="isManage" class="link" @click="showUpdateField('language', project.language)">更改</span>
          </div>

          <div class="info-item">
            <span>{{ project.publisher }}</span>
            <span v-if="isManage" class="link" @click="showUpdateField('publisher', project.publisher)">更改</span>
          </div>

          <div class="info-item">
            <span>
              <span v-for="(label, index) in project.label_list" :key="index">
                {{ label }}{{ index < project.label_list.length - 1 ? '，' : '' }}
              </span>
            </span>
            <span v-if="isManage" class="link" @click="showUpdateField('label_list', project.label_list)">更改</span>
          </div>

          <div class="info-item">
            <span>{{ project.topic }}</span>
            <span v-if="isManage" class="link" @click="showUpdateField('topic', project.topic)">更改</span>
          </div>

          <div class="info-item">
            <span>{{ project.editor }}</span>
            <span v-if="isManage" class="link" @click="showUpdateField('editor', project.editor)">更改</span>
          </div>
        </div>
      </div>

      <div class="table-twocolumn">
        <span class="label">内容简介</span>
        <div class="project-item">
          <span>{{ project.content_intro }}</span>
          <span v-if="isManage" class="link" @click="showUpdateField('content_intro', project.content_intro)">
            更改
          </span>
        </div>
        <span class="label">选题背景</span>
        <div class="project-item">
          <span>{{ project.background }}</span>
          <span v-if="isManage" class="link" @click="showUpdateField('background', project.background)">更改</span>
        </div>
        <span class="label">作者简介</span>
        <div class="project-item">
          <span>{{ project.author_intro }}</span>
          <span v-if="isManage" class="link" @click="showUpdateField('author_intro', project.author_intro)">更改</span>
        </div>
      </div>

      <div class="table-fourcolumn">
        <span class="label" style="line-height: 16px">预计容量<br />（课数）</span>
        <div class="project-item">
          <span>{{ project.content_count_YG }}</span>
          <span v-if="isManage" class="link" @click="showUpdateField('content_count_YG', project.content_count_YG)">
            更改</span
          >
        </div>
        <span class="label">预计字数</span>
        <div class="project-item">
          <span>{{ project.word_count_YG }}</span>
          <span v-if="isManage" class="link" @click="showUpdateField('word_count_YG', project.word_count_YG)">
            更改</span
          >
        </div>
        <span class="label">计划出版日期</span>
        <div class="project-item">
          <span>{{ project.plan_publish_date }}</span>
          <span v-if="isManage" class="link" @click="showUpdateField('plan_publish_date', project.plan_publish_date)">
            更改</span
          >
        </div>
        <span class="label">读者对象</span>
        <div class="project-item">
          <span>{{ project.reader }}</span>
          <span v-if="isManage" class="link" @click="showUpdateField('reader', project.reader)">更改</span>
        </div>
        <span class="label">项目组长</span>
        <div class="project-item">
          <span>{{ project.leader_name_desc }}</span>
          <span v-if="isManage" class="link" @click="selectLeader">更改</span>
        </div>
        <span class="label">项目成员</span>
        <div class="project-item">
          <span>{{ project.member_name_desc }}</span>
          <span v-if="isManage" class="link" @click="selectMembers">更改</span>
        </div>
        <span class="label">创建人</span>
        <div class="project-item">
          <span>{{ project.creator_name }}</span>
        </div>
        <span class="label">创建时间</span>
        <div class="project-item">
          <span>{{ project.create_time }}</span>
        </div>
      </div>
    </main>

    <SelectMembers
      :visible.sync="visibleMembers"
      :title="selectMembersTitle"
      :selected-list="list[type]"
      :type="type"
      @confirm="handleSelectedMembers"
    />
    <UpdateProjectField
      :visible.sync="visibleUpdateField"
      :project-id="id"
      :field="curField"
      :value="curFieldValue"
      @updateProjectFieldValue="updateProjectFieldValue"
    />
  </div>
</template>

<script>
import {
  GetProjectInfo,
  SetProjectMember,
  SetProjectLeader,
  UpdateProjectFieldValue,
  SetProjectLabel,
} from '@/api/project';
import { GetUserList_ID } from '@/api/user';

import SelectMembers from '@/views/create_project/selectProjectMembers.vue';
import MenuPage from '@/views/personal_workbench/common/menu.vue';
import UpdateProjectField from './components/UpdateProjectField.vue';
import ProjectMenu from '@/views/project_manage/common/ProjectMenu.vue';

export default {
  name: 'ProjectInfoManage',
  components: {
    SelectMembers,
    MenuPage,
    UpdateProjectField,
    ProjectMenu,
  },
  data() {
    console.log(this.$route.query);

    return {
      id: this.$route.params.id,
      isManage: this.$route.query.isManage === 'true', // 是否为管理模式
      backPath: this.$route.query.backPath || '/personal_workbench/project',
      labelInput: '',
      selectMembersTitle: '',
      visibleMembers: false,
      type: '',
      list: {
        leader: [],
        member: [],
      },
      project: {
        name: '',
        category: '',
        label_list: [],
        language: '',
        topic: '',
        publisher: '',
        content_intro: '',
        background: '',
        author_intro: '',
        content_count_YG: 100,
        word_count_YG: 100000,
        plan_publish_date: '', // 计划出版日期
        reader: '', // 读者对象
        leader_id_list: [], // 组长列表
        leader_name_desc: '', // 组长名称描述
        member_id_list: [], // 组员列表
        member_name_desc: '', // 组员名称描述
        creator_name: '', // 创建人名称
        create_time: '', // 创建时间
        editor: '', // 作者
        cover_image_file_id: null, // 封面图片ID
        cover_image_file_url: '', // 封面图片URL
      },
      visibleUpdateField: false,
      curField: '',
      curFieldValue: '',
    };
  },
  created() {
    this.getProjectInfo();
  },
  methods: {
    getProjectInfo() {
      GetProjectInfo({ id: this.id }).then(({ project_info, member_list, leader_list }) => {
        this.project = project_info;
        this.project.leader_name_desc = leader_list.map((user) => user.name).join('，');
        this.project.member_name_desc = member_list.map((user) => user.name).join('，');
        this.getUserList_ID(project_info.leader_id_list, 'leader');
        this.getUserList_ID(project_info.member_id_list, 'member');
      });
    },
    // 处理标签输入
    labelChange() {
      if (this.labelInput.trim() !== '') {
        this.project.label_list.push(this.labelInput.trim());
        this.labelInput = ''; // 清空输入框
      }
    },
    selectLeader() {
      this.selectMembersTitle = '选择组长';
      this.type = 'leader';
      this.visibleMembers = true;
    },
    selectMembers() {
      this.selectMembersTitle = '选择项目成员';
      this.type = 'member';
      this.visibleMembers = true;
    },
    /**
     * 处理选择的成员
     * @param {Array} selectedUsers - 选中的用户列表
     */
    handleSelectedMembers(selectedUsers) {
      if (this.type === 'leader') {
        this.project.leader_id_list = selectedUsers.map((user) => user.id);
        this.setProjectLeader();
      } else if (this.type === 'member') {
        this.project.member_id_list = selectedUsers.map((user) => user.id);
        this.setProjectMember();
      }
    },
    /**
     * 得到用户列表（指定ID）
     * @param {Array} id_list - 用户ID列表
     * @param {string} type - 用户类型（组长或组员）
     */
    getUserList_ID(id_list, type) {
      GetUserList_ID({ id_list }).then(({ user_list }) => {
        if (type === 'leader') {
          this.list.leader = user_list;
        } else if (type === 'member') {
          this.list.member = user_list;
        }
      });
    },
    // 设置项目成员
    setProjectMember() {
      SetProjectMember({
        project_id: this.id,
        user_id_list: this.project.member_id_list,
      }).then(() => {
        this.$message.success('项目成员更新成功');
        this.getProjectInfo();
      });
    },
    // 设置项目组长
    setProjectLeader() {
      SetProjectLeader({
        project_id: this.id,
        user_id_list: this.project.leader_id_list,
      }).then(() => {
        this.$message.success('项目组长更新成功');
        this.getProjectInfo();
      });
    },
    /**
     * 显示更新字段对话框
     * @param {string} field - 字段名称
     * @param {any} value - 当前字段值
     */
    showUpdateField(field, value) {
      this.curField = field;
      this.curFieldValue = value;
      this.visibleUpdateField = true;
    },
    /**
     * 更新项目字段值
     * @param {string} field_name - 字段名称
     * @param {any} value - 新的字段值
     */
    updateProjectFieldValue(field_name, value) {
      if (field_name === 'label_list') {
        SetProjectLabel({
          project_id: this.id,
          label_list: value,
        }).then(() => {
          this.$message.success('项目标签更新成功');
          this.getProjectInfo();
        });
        return;
      }

      UpdateProjectFieldValue({
        project_id: this.id,
        field_name,
        value,
      }).then(() => {
        this.$message.success('项目更新成功');
        this.getProjectInfo();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@use '@/styles/mixin.scss' as *;

.project-info {
  @include page-content(true);

  &__header {
    .name {
      width: 240px;
      font-size: 16px;
      font-weight: bold;
    }
  }

  &-manage {
    row-gap: 0 !important;
    max-width: 1148px;
    margin: 0 auto !important;

    .table-fourcolumn,
    .table-twocolumn {
      display: grid;

      .label,
      .project-item {
        padding: 4px 8px;
        line-height: 32px;
        border-bottom: $border;
      }

      .label {
        text-align: right;
        background-color: $fill-color;

        &.label-list {
          display: flex;
          flex-direction: column;
          row-gap: 18px;
          padding: 12px 8px;
        }
      }

      .project-item {
        display: flex;
        column-gap: 8px;

        :first-child {
          flex: 1;
        }

        &.info-list {
          flex-direction: column;
          padding: 3px 8px;

          :first-child {
            flex: none;
          }

          .info-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 50px;
            padding: 9px 0;

            &:not(:last-child) {
              border-bottom: $border;
            }
          }
        }

        .cover-image {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 373px;
          height: 248px;
          overflow: hidden;

          img {
            display: block;
            flex: none;
            max-width: 373px;
            max-height: 248px;
          }
        }
      }
    }

    .table-fourcolumn:first-child {
      grid-template-rows: 40px 258px;
      grid-template-columns: 120px 1fr 120px 1fr;
    }

    .table-fourcolumn:nth-child(3) {
      grid-template-rows: repeat(2, minmax(40px, auto));
      grid-template-columns: 120px 1fr 120px 1fr;
    }

    .table-twocolumn {
      grid-template-rows: repeat(3, minmax(40px, auto));
      grid-template-columns: 120px 1fr;
    }
  }
}
</style>
