<template>
  <div class="content-box" v-loading="loading">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">项目管理</span>
    </div>
    <div class="middle">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
        <!-- <el-tab-pane label="我关注的" name="1">我关注的</el-tab-pane> -->
        <el-tab-pane label="我负责的" name="3">我负责的</el-tab-pane>
        <el-tab-pane label="我协办的" name="4">我协办的</el-tab-pane>
        <el-tab-pane
          label="我创建的"
          name="5"
          v-if="btnFlag('project-wochuangjiande')"
          >我创建的</el-tab-pane
        >
        <el-tab-pane
          label="我分管的"
          name="6"
          v-if="btnFlag('project-wofenguande')"
          >我分管的</el-tab-pane
        >
      </el-tabs>
    </div>
    <div class="filter" id="filter" @scroll="projectScroll">
      <div class="condition">
        <div class="fil" v-if="activeName == 5 || activeName == 6">
          <span>主办单位</span>&nbsp;&nbsp;
          <el-cascader
            :options="searchOrganizeData"
            :props="searchOrganizeProp"
            @change="getUser1"
            clearable
          >
            <template #default="{ node, data }">
              <span>{{ data.userName }}</span>
              <span v-if="!node.isLeaf"> ({{ data.userList.length }}) </span>
            </template>
          </el-cascader>
        </div>
        <div class="fil" v-if="activeName == 5 || activeName == 6">
          <span>协办单位</span>&nbsp;&nbsp;
          <el-cascader
            :options="searchOrganizeData"
            :props="searchOrganizeProp"
            @change="getUser2"
            clearable
          >
            <template #default="{ node, data }">
              <span>{{ data.userName }}</span>
              <span v-if="!node.isLeaf"> ({{ data.userList.length }}) </span>
            </template>
          </el-cascader>
        </div>
        <!-- <div class="fil" v-show="activeName==5||activeName==6">
          <span>主办单位</span>&nbsp;&nbsp;
          <el-select
            v-model="searchInput.organize"
            placeholder="请选择主办单位"
            style="width: 160px"
            clearable
            @change="getUser1"
          >
            <el-option
              v-for="item in departmentData"
              :key="item.oname"
              :label="item.oname"
              :value="item.oname"
            />
          </el-select>
        </div>
        <div class="fil" v-show="activeName==5||activeName==6">
          <span>主办人</span>&nbsp;&nbsp;
          <el-select
            v-model="searchInput.sposonerName"
            placeholder="请选择主办人"
            style="width: 160px"
            clearable
          >
            <el-option
              v-for="item in userData1"
              :key="item.id"
              :label="item.userName"
              :value="item.userName"
            />
          </el-select>
        </div>
        <div class="fil" v-show="activeName==5||activeName==6">
          <span>协办单位</span>&nbsp;&nbsp;
          <el-select
            v-model="searchInput.coOrganize"
            placeholder="请选择协办单位"
            style="width: 160px"
            clearable
            @change="getUser2"
          >
            <el-option
              v-for="item in departmentData"
              :key="item.oname"
              :label="item.oname"
              :value="item.oname"
            />
          </el-select>
        </div>
        <div class="fil" v-show="activeName==5||activeName==6">
          <span>协办人</span>&nbsp;&nbsp;
          <el-select
            v-model="searchInput.coSposonerName"
            placeholder="请选择协办人"
            style="width: 160px"
            clearable
          >
            <el-option
              v-for="item in userData2"
              :key="item.id"
              :label="item.userName"
              :value="item.userName"
            />
          </el-select>
        </div> -->
        <div class="fil">
          <span>项目等级</span>&nbsp;&nbsp;
          <el-select
            v-model="searchInput.projectLevel"
            placeholder="请选择项目等级"
            style="width: 160px"
            clearable
            @change="searchBtn"
          >
            <el-option
              v-for="item in projectLevelData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="fil">
          <span>项目来源</span>&nbsp;&nbsp;
          <el-select
            v-model="searchInput.projectFrom"
            placeholder="请选择项目来源"
            style="width: 160px"
            clearable
            @change="searchBtn"
          >
            <el-option
              v-for="item in projectOriginData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="fil">
          <span>状态</span>&nbsp;&nbsp;
          <el-select
            v-model="searchInput.state"
            placeholder="请选择状态"
            style="width: 160px"
            clearable
            @change="searchBtn"
          >
            <el-option
              v-for="item in stateData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="fil">
          <span>创建时间 </span>&nbsp;&nbsp;
          <el-date-picker
            v-model="searchInput.createTime"
            type="daterange"
            unlink-panels
            range-separator="-"
            start-placeholder="起始时间"
            end-placeholder="截止时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :prefix-icon="Calendar"
            placeholder="请选择日期"
            style="width: 280px"
            @change="searchBtn"
          />
        </div>
        <div class="fil">
          <span>项目周期 </span>&nbsp;&nbsp;
          <el-date-picker
            v-model="searchInput.periodTime"
            type="daterange"
            unlink-panels
            range-separator="-"
            start-placeholder="起始时间"
            end-placeholder="截止时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :prefix-icon="Calendar"
            placeholder="请选择日期"
            style="width: 280px"
            @change="searchBtn"
          />
        </div>
        <div class="fil">
          <span>完成时间 </span>&nbsp;&nbsp;
          <el-date-picker
            v-model="searchInput.finishTime"
            type="daterange"
            unlink-panels
            range-separator="-"
            start-placeholder="起始时间"
            end-placeholder="截止时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :prefix-icon="Calendar"
            placeholder="请选择日期"
            style="width: 280px"
            @change="searchBtn"
          />
        </div>
        <div class="fil">
          <span>是否已评分</span>&nbsp;&nbsp;
          <el-select
            v-model="searchInput.scoreState"
            placeholder="请选择"
            style="width: 160px"
            clearable
            @change="searchBtn"
          >
            <el-option label="已评分" value="1" />
            <el-option label="未评分" value="0" />
          </el-select>
        </div>
        <div class="fil">
          <span>是否已关注</span>&nbsp;&nbsp;
          <el-select
            v-model="searchInput.collect"
            placeholder="请选择"
            style="width: 160px"
            clearable
            @change="searchBtn"
          >
            <el-option label="收藏" value="1" />
            <el-option label="未收藏" value="0" />
          </el-select>
        </div>
        <div class="fil">
          <span>是否有任务</span>&nbsp;&nbsp;
          <el-select
            v-model="searchInput.hasTask"
            placeholder="请选择"
            style="width: 160px"
            clearable
            @change="searchBtn"
          >
            <el-option label="有任务" value="1" />
            <el-option label="没有任务" value="0" />
          </el-select>
        </div>
        <div class="fil">
          <span>是否我评分</span>&nbsp;&nbsp;
          <el-select
            v-model="searchInput.isScore"
            placeholder="请选择"
            style="width: 160px"
            clearable
            @change="searchBtn"
          >
            <el-option label="是我" value="1" />
            <el-option label="不是我" value="0" />
          </el-select>
        </div>
        <div class="fil">
          <span>项目名称 </span>&nbsp;&nbsp;
          <el-input
            clearable
            v-model="searchInput.projectName"
            class="w-50 m-2"
            placeholder="请输入项目名称"
            style="width: 160px"
            @clear="searchBtn"
          />
        </div>
        <div class="fil">
          <el-button type="primary" class="search" @click="searchBtn"
            >查询</el-button
          >
          <el-button
            type="primary"
            class="search"
            @click="addProjectbtn"
            v-if="
              (activeName == 5 || activeName == 6) &&
              btnFlag('project-chuangjianxiangmu')
            "
            >创建项目</el-button
          >
          <el-button
            v-if="
              (activeName == 5 || activeName == 6) &&
              btnFlag('project-yijiancuiban')
            "
            type="primary"
            class="search"
            @click="urgeProject"
            >一键催办</el-button
          >
          <!-- <el-button @click="searchBtn" color="rgba(33, 107, 255, 1)" plain
            >批量导入</el-button
          > -->
          <!-- <el-popconfirm
            v-if="
              (activeName == 5 || activeName == 6) &&
              btnFlag('project-yijiancuiban')
            "
            width="200"
            confirm-button-text="确认"
            cancel-button-text="取消"
            :icon="InfoFilled"
            icon-color="#f89626"
            title="是否催办所有项目?"
            @confirm="urgeProject"
            @cancel="cancelEvent"
          >
            <template #reference>
              <el-button type="primary" class="search">一键催办</el-button>
            </template>
          </el-popconfirm> -->

          <!-- <el-button @click="searchBtn" color="rgba(212, 48, 48, 1)"
            >删除</el-button
          > -->
          <!-- <el-button type="primary" class="search" @click="searchBtn"
            >导出</el-button
          > -->
        </div>
      </div>
      <div class="project">
        <el-card v-for="i in tableData.list" @click="projectCard(i)">
          <div class="title">
            <div class="name">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="i.projectName"
                placement="top-start"
              >
                <span class="projectName">{{ i.projectName }}</span>
              </el-tooltip>
              <span class="shewai">{{ i.projectFrom }}</span>
              <!-- <span class="jinji">紧急</span> -->
            </div>
            <div class="btn">
              <div
                class="jinji"
                @click.stop=""
                size="small"
                color="rgba(212, 48, 48, 1)"
              >
                {{ i.projectLevel }}
              </div>
              <el-button
                v-if="i.collect == 1 && btnFlag('project-shoucangxiangmu')"
                @click.stop="collectClick(i)"
                size="small"
                color="rgba(254, 144, 51, 1)"
                >已收藏</el-button
              >
              <el-button
                v-if="i.collect == 0 && btnFlag('project-shoucangxiangmu')"
                @click.stop="collectClick(i)"
                size="small"
                color="rgba(254, 144, 51, 1)"
                >收藏</el-button
              >
              <el-dropdown
                placement="bottom-start"
                v-if="activeName == 5 || activeName == 6"
              >
                <el-button
                  @click.stop=""
                  size="small"
                  color="rgba(33, 107, 255, 1)"
                  >更多</el-button
                >
                <template #dropdown>
                  <el-dropdown-menu>
                    <!-- <el-dropdown-item>复制</el-dropdown-item> -->
                    <el-dropdown-item
                      @click.stop="editProject(i)"
                      v-if="activeName == 5 && btnFlag('project-xiugaixiangmu')"
                      >编辑</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.stop="delProject(i)"
                      v-if="
                        activeName == 5 && btnFlag('project-shanchuxiangmu')
                      "
                      >删除</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="
                        activeName == 6 &&
                        isScorer(i) &&
                        btnFlag('project-pingfen')
                      "
                      @click.stop="scoreProject(i)"
                      >评分</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          <div class="info">
            <div class="item">主办单位：{{ i.organize }}</div>
            <div class="item">主办人：{{ i.sposonerName }}</div>
            <div class="item">协办人：{{ i.coSposonerName }}</div>
            <div class="item">
              项目周期：{{ i.startTime }} ~ {{ i.endTime }}
            </div>
            <!-- <div class="item">人员：{{ i.staffNum }}人</div> -->
            <div>任务：{{ i.taskNum }}个</div>
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <div>
                <div class="item">预警次数：{{ i.warnNum }}次</div>
                <div class="item">提醒次数：{{ i.remindNum }}次</div>
              </div>
              <span class="score">{{ i.score }}<span style="font-size: 18px;">分</span></span>
            </div>
            <div class="plan">
              <span>项目进度：</span>
              <el-progress
                :percentage="i.progress*100"
                color="rgba(0, 97, 255, 1)"
              />
              <img
                v-if="
                  (activeName == 5 || activeName == 6) &&
                  btnFlag('project-cuiban')
                "
                title="催办"
                @click.stop="urgeOneProject(i)"
                src="../../assets/images/inform.png"
                alt=""
              />
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <!-- 新建项目 -->
    <el-dialog
      class="project"
      v-model="projectVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="projectTitle"
      align-center
      width="600"
      :before-close="cancelProject"
    >
      <el-form
        ref="projectRef"
        :model="projectRuleForm"
        :rules="projectRules"
        class="demo-ruleForm"
        label-width="80px"
        :size="formSize"
        label-position="right"
        status-icon
      >
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="projectRuleForm.projectName"
            placeholder="请输入项目名称"
            maxlength="50"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="项目描述" prop="projectContent">
          <el-input
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 8 }"
            v-model="projectRuleForm.projectContent"
            placeholder="请输入描述"
            clearable
          />
        </el-form-item>
        <el-form-item label="上传附件">
          <!-- <el-input
            v-model="projectRuleForm.attachment"
            placeholder="请上传附件"
          >
            <template #append>
              <el-button
                style="
                  width: 100px;
                  background-color: rgba(33, 107, 255, 1);
                  color: #fff;
                "
                >上传</el-button
              >
            </template>
          </el-input> -->
          <div class="fujian">
            <el-upload
              class="avatar-uploader"
              action=""
              :on-change="handleChange"
              :http-request="handleUpload"
            >
              <el-button type="primary">上传附件</el-button>
              <!-- <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500KB.
              </div>
            </template> -->
            </el-upload>
            <div v-if="fileList" class="fileList">
              <div class="files" v-for="i in fileList">
                {{ i
                }}<el-icon @click="delFiles(i)" size="18">
                  <CircleClose />
                </el-icon>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="主办人员" prop="sposoner">
          <!-- <el-cascader :props="props" :options="options" /> -->
          <el-cascader
            :options="organizeData"
            :props="organizeProps"
            @change="organizeChange"
            v-model="sposonerVal"
          >
            <template #default="{ node, data }">
              <span>{{ data.userName }}</span>
              <span v-if="!node.isLeaf"> ({{ data.userList.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="协办人员" prop="coSposoner">
          <!-- <el-cascader :props="props" :options="options" /> -->
          <el-cascader
            :options="organizeData"
            :props="coOrganizeProps"
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="3"
            clearable
            @change="coOrganizeChange"
            v-model="coSposonerVal"
          >
            <template #default="{ node, data }">
              <span>{{ data.userName }}</span>
              <span v-if="!node.isLeaf"> ({{ data.userList.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
        <!-- <el-form-item label="主办单位" prop="organize">
          <el-select
            v-model="projectRuleForm.organize"
            placeholder="请选择主办单位"
            clearable
            @change="getUser3"
          >
            <el-option
              v-for="item in departmentData"
              :key="item.oname"
              :label="item.oname"
              :value="item.oname"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主办人" prop="sposoner">
          <el-select
            v-model="projectRuleForm.sposoner"
            placeholder="请选择主办人"
            clearable
          >
            <el-option
              v-for="item in userData3"
              :key="item.id"
              :label="item.userName"
              :value="item.id.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="协办单位" prop="coOrganize">
          <el-select
            v-model="projectRuleForm.coOrganize"
            placeholder="请选择协办单位"
            clearable
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="3"
            @change="getUser4"
          >
            <el-option
              v-for="item in departmentData"
              :key="item.oname"
              :label="item.oname"
              :value="item.oname"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="协办人" prop="coSposoner">
          <el-select
            v-model="projectRuleForm.coSposoner"
            placeholder="请选择协办人"
            clearable
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="5"
          >
            <el-option
              v-for="item in userData4"
              :key="item.id"
              :label="item.userName"
              :value="item.id.toString()"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="项目来源" prop="projectFrom">
          <el-select
            v-model="projectRuleForm.projectFrom"
            placeholder="请选择项目来源"
            clearable
          >
            <el-option
              v-for="item in projectOriginData"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目等级" prop="projectLevel">
          <el-select
            v-model="projectRuleForm.projectLevel"
            placeholder="请选择项目等级"
            clearable
          >
            <el-option
              v-for="item in projectLevelData"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="评分人" prop="scorer">
          <el-select
            v-model="projectRuleForm.scorer"
            placeholder="请选择评分人"
            clearable
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="6"
          >
            <el-option
              v-for="item in scorerData"
              :key="item.id"
              :label="item.userName"
              :value="item.id.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="options">
          <el-button
            class="queding"
            type="primary"
            @click="confirmProject(projectRef)"
          >
            &nbsp;&nbsp;确认&nbsp;&nbsp;
          </el-button>
          <el-button class="quxiao" @click="cancelProject"
            >&nbsp;&nbsp;取消&nbsp;&nbsp;</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 评分 -->
    <el-dialog
      class="project"
      v-model="scoreVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="评分"
      align-center
      width="600"
      :before-close="cancelScore"
    >
      <el-form
        ref="scoreRef"
        :model="scoreRuleForm"
        :rules="scoreRules"
        class="demo-ruleForm"
        label-width="60px"
        :size="formSize"
        label-position="right"
        status-icon
      >
        <el-form-item label="评价" prop="describe">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            v-model="scoreRuleForm.describe"
            placeholder="请输入评价"
            clearable
          />
        </el-form-item>
        <el-form-item label="评分" prop="num">
          <el-input v-model="scoreRuleForm.num" placeholder="请输入评分" />
        </el-form-item>
        <el-form-item class="options">
          <el-button
            class="queding"
            type="primary"
            @click="confirmScore(scoreRef)"
          >
            &nbsp;&nbsp;确认&nbsp;&nbsp;
          </el-button>
          <el-button class="quxiao" @click="cancelScore"
            >&nbsp;&nbsp;取消&nbsp;&nbsp;</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 点击卡片弹窗 -->
    <el-dialog
      class="projectCard"
      v-model="cardVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="cardTitle"
      align-center
      width="1400"
      :before-close="cancelCard"
    >
      <div>
        <div class="title">项目情况</div>
        <div class="info">{{ cardInfo.projectContent }}</div>
        <el-divider />
        <div class="unit">
          <div class="unit_i">
            <span class="key">主办单位 :</span>
            <span class="value">{{ cardInfo.organize }}</span>
          </div>
          <div class="unit_i">
            <span class="key">主办人 :</span>
            <span class="value">{{ cardInfo.sposonerName }}</span>
          </div>
          <div class="unit_i">
            <span class="key">协办单位 :</span>
            <span class="value">{{ cardInfo.coOrganizeCopy }}</span>
          </div>
          <div class="unit_i">
            <span class="key">协办人 :</span>
            <span class="value">{{ cardInfo.coSposonerName }}</span>
          </div>
          <div class="unit_i">
            <span class="key">分管领导 :</span>
            <span class="value">{{ cardInfo.leaderName }}</span>
          </div>
          <div class="unit_i">
            <span class="key">评分人 :</span>
            <span class="value">{{ cardInfo.scorerName }}</span>
          </div>
          <div class="unit_i">
            <span class="key">项目周期 :</span>
            <span class="value"
              >{{ cardInfo.startTime }} ~ {{ cardInfo.endTime }}</span
            >
          </div>
          <div class="unit_i">
            <span class="key">项目等级 :</span>
            <span class="value">{{ cardInfo.projectLevel }}</span>
          </div>
          <div class="unit_i">
            <span class="key">项目来源 :</span>
            <span class="value">{{ cardInfo.projectFrom }}</span>
          </div>
        </div>
        <div class="unit" style="margin: 10px 0 20px">
          <div class="unit_i">
            <span class="key">附件 :</span>
            <div class="fileList">
              <div class="attachment" v-for="i in cardInfo.fileUrl">
                <span @click="pdfChange(i)">{{ i }}</span>
                <!-- <img style="height: 40px" :src="i" alt="" /> -->
              </div>
            </div>
          </div>
        </div>
        <div class="participation">
          <el-button @click="logChange(1)" :class="logFlag == 1 ? 'active' : ''"
            >项目进度</el-button
          >
          <el-button @click="logChange(2)" :class="logFlag == 2 ? 'active' : ''"
            >项目日志</el-button
          >
        </div>
        <div v-if="logFlag == 1">
          <div class="schedule">
            <span>任务进度分（权重{{ cardInfo.progress }}%）</span>
            <!-- <span>（注：评分维度为：任务完成质量40%）</span> -->
          </div>
          <el-table
            :row-class-name="tableRowClassName"
            :data="taskData"
            @selection-change="handleSelectionChange"
            style="width: 100%"
            :header-cell-style="{
              background: 'rgba(240, 243, 247, 1)',
              height: '40px',
              border: 0,
            }"
          >
            <!-- <el-table-column type="selection" width="55" /> -->
            <el-table-column align="center" prop="taskName" label="任务名称" />
            <el-table-column
              align="center"
              width="250"
              tooltip-effect
              label="附件"
            >
              <template #default="scope">
                <div v-if="scope.row.fileUrl">
                  <div v-for="i in scope.row.fileUrl.split(',')">
                    <div
                      style="color: rgba(33, 107, 255, 1); cursor: pointer"
                      @click="pdfChange(i)"
                    >
                      {{ i }}
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="状态">
              <template #default="scope">
                <span v-if="scope.row.state == 1">正常在办</span>
                <span v-if="scope.row.state == 2">预警在办</span>
                <span v-if="scope.row.state == 3">超时在办</span>
                <span v-if="scope.row.state == 4">正常办结</span>
                <span v-if="scope.row.state == 5">超时办结</span>
                <!-- 1、正常在办，2、预警在办，3、超时在办，4、正常办结，5、超时办结  -->
              </template>
            </el-table-column>
            <el-table-column align="center" width="120" label="起止时间">
              <template #default="scope">
                <span>{{ scope.row.startTime }} ~ {{ scope.row.endTime }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="remindTime"
              label="提醒时间"
              width="120"
            />
            <el-table-column
              align="center"
              width="120"
              prop="warnTime"
              label="预警时间"
            />
            <el-table-column
              align="center"
              width="120"
              prop="finishTime"
              label="完成时间"
            />
            <el-table-column
              align="center"
              width="120"
              prop="finishRemark"
              tooltip-effect
              label="完成备注"
            />
            <el-table-column
              align="center"
              prop="scoreStandard"
              label="评价标准"
              width="170"
            />
            <el-table-column align="center" prop="weight" label="权重" />
            <el-table-column
              align="center"
              prop="headerName"
              label="任务负责人"
              width="100"
            />
            <el-table-column
              align="center"
              prop="scoreLimit"
              label="评分上限"
            />
            <el-table-column align="center" prop="sysScore" label="系统" />
            <el-table-column align="center" label="操作" width="220">
              <template #default="scope">
                <div class="options">
                  <div
                    class="edit"
                    v-if="activeName == 5 && btnFlag('project-xiugairenwu')"
                    @click="editTask(scope.row)"
                  >
                    编辑
                  </div>
                  <el-popconfirm
                    v-if="activeName == 5 && btnFlag('project-shanchurenwu')"
                    width="200"
                    confirm-button-text="确认"
                    cancel-button-text="取消"
                    :icon="InfoFilled"
                    icon-color="#f89626"
                    title="是否删除此数据?"
                    @confirm="delTask(scope.row)"
                    @cancel="cancelEvent"
                  >
                    <template #reference>
                      <div class="del">删除</div>
                    </template>
                  </el-popconfirm>
                  <el-popconfirm
                    width="200"
                    confirm-button-text="确认"
                    cancel-button-text="取消"
                    :icon="InfoFilled"
                    icon-color="#f89626"
                    title="是否对此项目催办?"
                    @confirm="urgeTask(scope.row)"
                    @cancel="cancelEvent"
                    v-if="
                      (activeName == 5 || activeName == 6) &&
                      btnFlag('project-cuibanrenwu')
                    "
                  >
                    <template #reference>
                      <div class="look">催办</div>
                    </template>
                  </el-popconfirm>
                  <div
                    class="edit"
                    v-if="
                      (activeName == 3 || activeName == 4) &&
                      scope.row.header == userId &&
                      btnFlag('project-renwugengxinjindu')
                    "
                    @click="updateTask(scope.row)"
                  >
                    更新进度
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            type="primary"
            class="search"
            @click="addTaskbtn"
            v-if="activeName == 5"
            >添加任务</el-button
          >
          <el-button
            v-if="activeName == 6 && isScorer()"
            type="primary"
            class="search"
            @click="scoreProjects"
            >评分</el-button
          >
        </div>
        <div v-if="logFlag == 2">
          <el-table
            :row-class-name="tableRowClassName"
            :data="logData"
            @selection-change="handleSelectionChange"
            style="width: 100%"
            :header-cell-style="{
              background: 'rgba(240, 243, 247, 1)',
              height: '40px',
              border: 0,
            }"
          >
            <!-- <el-table-column type="selection" width="55" /> -->
            <el-table-column align="center" prop="taskName" label="任务名称" />
            <el-table-column align="center" label="附件">
              <template #default="scope">
                <div v-if="scope.row.fileUrl">
                  <div v-for="i in scope.row.fileUrl.split(',')">
                    <div
                      style="color: rgba(33, 107, 255, 1); cursor: pointer"
                      @click="pdfChange(i)"
                    >
                      {{ i }}
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="content" label="内容" />
            <el-table-column
              align="center"
              prop="createTime"
              label="发生时间"
            />
            <el-table-column align="center" prop="createBy" label="操作人" />
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 新建任务 -->
    <el-dialog
      class="project"
      v-model="taskVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="taskTitle"
      align-center
      width="620"
      :before-close="cancelTask"
    >
      <el-form
        ref="taskRef"
        :model="taskRuleForm"
        :rules="taskRules"
        class="demo-ruleForm"
        label-width="95px"
        :size="formSize"
        label-position="right"
        status-icon
      >
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="taskRuleForm.taskName"
            placeholder="请输入任务名称"
            maxlength="50"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="评分标准" prop="scoreStandard">
          <el-input
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 8 }"
            v-model="taskRuleForm.scoreStandard"
            placeholder="请输入评分标准"
            clearable
          />
        </el-form-item>
        <el-form-item label="上传附件">
          <div class="fujian">
            <el-upload
              class="avatar-uploader"
              action=""
              :on-change="handleChange"
              :http-request="handleUploadTask"
            >
              <el-button type="primary">上传附件</el-button>
              <!-- <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500KB.
              </div>
            </template> -->
            </el-upload>
            <div v-if="fileListTask" class="fileList">
              <div class="files" v-for="i in fileListTask">
                {{ i
                }}<el-icon @click="delFilesTask(i)" size="18">
                  <CircleClose />
                </el-icon>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="评分上限" prop="scoreLimit">
          <el-input
            v-model="taskRuleForm.scoreLimit"
            placeholder="请输入评分上限"
          />
        </el-form-item>
        <el-form-item label="权重(%)" prop="weight">
          <el-input v-model="taskRuleForm.weight" placeholder="请输入权重" />
        </el-form-item>
        <el-form-item label="提醒时间" prop="remindTime">
          <el-date-picker
            v-model="taskRuleForm.remindTime"
            type="datetime"
            placeholder="选择提醒时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @update:modelValue="handleDateChange" 
            :disabled-date="disabledDateFn"
            :disabled-hours="disabledHours"
            :disabled-minutes="disabledMinutes" 
            :disabled-seconds="disabledSeconds"
            :default-time="new Date()" 
          />
        </el-form-item>
        <el-form-item label="预警时间" prop="warnTime">
          <el-date-picker
            v-model="taskRuleForm.warnTime"
            type="datetime"
            placeholder="选择预警时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @update:modelValue="handleDateChange"
            :disabled-date="disabledDateFn"
            :disabled-hours="disabledHours"
            :disabled-minutes="disabledMinutes" 
            :disabled-seconds="disabledSeconds"
            :default-time="new Date()" 
          />
        </el-form-item>
        <el-form-item label="任务负责人" prop="header">
          <el-select
            v-model="taskRuleForm.header"
            placeholder="请选择任务负责人"
            clearable
          >
            <el-option
              v-for="item in taskLeader"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务周期" prop="periodTime">
          <el-date-picker
            v-model="taskRuleForm.periodTime"
            type="datetimerange"
            range-separator="-"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :prefix-icon="Calendar"
            placeholder="请选择任务周期"
            style="width: 280px"
          />
        </el-form-item>
        <el-form-item class="options">
          <el-button
            class="queding"
            type="primary"
            @click="confirmTask(taskRef)"
          >
            &nbsp;&nbsp;确认&nbsp;&nbsp;
          </el-button>
          <el-button class="quxiao" @click="cancelTask"
            >&nbsp;&nbsp;取消&nbsp;&nbsp;</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 更新进度 -->
    <el-dialog
      class="project"
      v-model="updateVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="更新进度"
      align-center
      width="600"
      :before-close="cancelUpdate"
    >
      <el-form
        ref="updateRef"
        :model="updateRuleForm"
        :rules="updateRules"
        class="demo-ruleForm"
        label-width="80px"
        :size="formSize"
        label-position="right"
        status-icon
      >
        <el-form-item label="完成备注" prop="remark">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            v-model="updateRuleForm.remark"
            placeholder="请输入备注"
            clearable
          />
        </el-form-item>
        <el-form-item label="上传附件">
          <el-upload
            class="avatar-uploader"
            action=""
            :on-change="handleChange"
            :http-request="handleAttachment"
          >
            <el-button type="primary">上传附件</el-button>
            <!-- <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500KB.
              </div>
            </template> -->
          </el-upload>
          <div v-if="fileListAttachment" class="fileList">
            <div class="files" v-for="i in fileListAttachment">
              {{ i
              }}<el-icon @click="delAttachment(i)" size="18">
                <CircleClose />
              </el-icon>
            </div>
          </div>
        </el-form-item>
        <el-form-item class="options">
          <el-button
            class="queding"
            type="primary"
            @click="confirmUpdate(updateRef)"
          >
            &nbsp;&nbsp;确认&nbsp;&nbsp;
          </el-button>
          <el-button class="quxiao" @click="cancelUpdate"
            >&nbsp;&nbsp;取消&nbsp;&nbsp;</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 预览pdf -->
    <el-dialog
      class="previewPdf"
      v-model="previewPdfVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="预览文档"
      width="1200"
      align-center
      :before-close="cancelPreviewPdf"
    >
      <!-- <vue-office-pdf 
          v-if="previewPdfUrl"
          :src="previewPdfUrl"
          /> -->
      <div class="pdfMain">
        <div class="home-box" v-if="previewPdfUrl">
          <div class="container" v-if="pdfFlag == 1">
            <!-- <iframe :src="previewPdfUrl" width="100%" height="100%"></iframe> -->
            <PDFViewer
              page-scale="page-fit"
              :width="1160"
              :height="800"
              theme="dark"
              :src="previewPdfUrl"
              @loaded="onLoaded"
            />
          </div>
          <div class="continer" v-if="pdfFlag == 2">
            <VueOfficeDocx :src="previewPdfUrl" />
          </div>
          <div class="continer" v-if="pdfFlag == 3">
            <img :src="previewPdfUrl" />
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  nextTick,
  onMounted,
  watch,
  onBeforeMount,
  onUnmounted,
  inject,
} from "vue";
import COS from "cos-js-sdk-v5";
import { useRouter } from "vue-router";
import { genFileId, ElMessage, ElMessageBox } from "element-plus";
import { Calendar, CircleClose } from "@element-plus/icons-vue";
import { dayjs } from "element-plus";
import lodash, { reduce } from "lodash";
import axios from "axios";
import { useStore } from "vuex";

import PDFViewer from "../../components/PDFViewer.vue";

// 导入依赖  word文档
import VueOfficeDocx from "@vue-office/docx";
// 导入样式文件
import "@vue-office/docx/lib/index.css";

const store = useStore();
const router = useRouter();
const btnFlag = inject("$btnFlag");
const userId = ref(); // 当前登录用户的id

const loading = ref(false);
const activeName = ref("3");

const searchInput = reactive({
  projectName: null, // 项目名称
  projectFrom: null, // 项目来源
  projectLevel: null, // 项目等级
  state: null, //
  organize: null, // 主办单位
  sposonerName: null, // 主办人
  coOrganize: null, // 协办单位
  coSposonerName: null, // 协办人
  createTime: null, // 创建时间
  periodTime: null, // 周期时间
  finishTime: null, // 完成时间
  scoreState: null, // 是否已评分：1已评分，0未评分，null全部
  collect: null, //    是否已关注，1收藏，0未收藏，null全部
  hasTask: null, //       是否有任务：1有任务，0没有任务，null全部
  isScore: null, //    是否我评分，1是我，0不是我，null全部
}); // 搜索按钮数据
const searchOrganizeProp = {
  children: "userList",
  label: "userName",
  value: "userName",
};

const currentPage = ref(1); // 当前页
const pageSize = ref(12);
const total = ref(40); // 当前总数
const totalPage = ref(1); // 当前总页数
const tableData = reactive({
  list: [{}],
});
const selectData = reactive({
  list: [],
}); // 多选框选择的数据
const api = ref("");

const projectOriginData = ref([
  { name: "涉内", id: "涉内" },
  { name: "涉外", id: "涉外" },
]); // 项目来源
const projectLevelData = ref([
  { name: "正常", id: "正常" },
  { name: "紧急", id: "紧急" },
]); // 项目等级
const departmentData = ref(); // 部门数据
const stateData = ref([
  { id: 1, name: "正常在办" },
  { id: 2, name: "预警在办" },
  { id: 3, name: "超时在办" },
  { id: 4, name: "正常办结" },
  { id: 5, name: "超时办结" },
]); // 用户数据

// 新建项目 (--------------------------------------------------------)
const projectVisible = ref(false);
const projectTitle = ref();
const projectRef = ref();

const searchOrganizeData = ref(); // 搜索框用主办协办人员
const organizeData = ref(); // 添加项目用主办协办人员
const scorerData = ref(); // 评分人

const organizeProps = {
  children: "userList",
  label: "userName",
  value: "id",
};
const coOrganizeProps = {
  multiple: true,
  children: "userList",
  label: "userName",
  value: "id",
};

const projectRuleForm = reactive({
  projectName: "", // 名称
  projectContent: "", // 描述
  fileUrl: "", // 附件

  organize: "", // 主办单位
  sposoner: "", // 主办人

  coOrganize: "", // 协办单位
  coSposoner: "", // 协办人

  projectFrom: "", // 项目来源
  projectLevel: "", // 项目等级
  scorer: "", // 评分人
  id: "",
});
const sposonerVal = ref([]); // 主办人和单位
const coSposonerVal = ref([]); // 协办人和单位

const fileList = ref([]);
// 新建项目表单验证
const projectRules = reactive({
  projectName: [
    { required: true, message: "项目名称不能为空", trigger: "blur" },
  ],
  projectContent: [
    { required: true, message: "项目描述不能为空", trigger: "blur" },
  ],
  fileUrl: [{ required: true, message: "附件不能为空", trigger: "blur" }],
  // organize: [{ required: true, message: "主办单位不能为空", trigger: "blur" }],
  sposoner: [{ required: true, message: "主办人不能为空", trigger: "blur" }],
  coSposoner: [{ required: true, message: "协办人不能为空", trigger: "blur" }],
  // coOrganize: [
  //   { required: true, message: "协办单位不能为空", trigger: "blur" },
  // ],
  projectFrom: [
    { required: true, message: "项目来源不能为空", trigger: "blur" },
  ],
  projectLevel: [
    { required: true, message: "项目等级不能为空", trigger: "blur" },
  ],
  scorer: [{ required: true, message: "评分人不能为空", trigger: "blur" }],
});

// 新建任务
const taskVisible = ref(false);
const taskTitle = ref();
const taskRef = ref();
const taskData = ref(); // 任务进度列表
const logData = ref(); // 任务日志

const taskRuleForm = reactive({
  taskName: "", // 任务名称
  projectId: "", // 项目ID
  scoreStandard: "", // 评价标准
  fileUrl: "", // 附件
  scoreLimit: "", // 评分上限
  weight: "", // 权重
  remindTime: "", // 提醒时间
  warnTime: "", // 预警时间
  header: "", // 负责人
  periodTime: "", // 周期-起始时间
  id: "",
});

const fileListTask = ref([]); // 任务列表
const taskLeader = ref(); // 任务负责人列表
// 新建项目表单验证
const taskRules = reactive({
  taskName: [{ required: true, message: "任务名称不能为空", trigger: "blur" }],
  scoreStandard: [
    { required: true, message: "评价标准不能为空", trigger: "blur" },
  ],
  fileUrl: [{ required: true, message: "附件不能为空", trigger: "blur" }],
  scoreLimit: [
    { required: true, message: "评分上限不能为空", trigger: "blur" },
  ],
  weight: [{ required: true, message: "权重不能为空", trigger: "blur" }],
  remindTime: [
    { required: true, message: "提醒时间不能为空", trigger: "blur" },
  ],
  warnTime: [{ required: true, message: "预警时间不能为空", trigger: "blur" }],
  header: [{ required: true, message: "任务负责人不能为空", trigger: "blur" }],
  periodTime: [
    { required: true, message: "任务周期不能为空", trigger: "blur" },
  ],
});

// 评分 (===========================================================)
const scoreVisible = ref(false);
const scoreRef = ref();
const scoreRuleForm = reactive({
  describe: "", // 描述
  num: "", // 分数
});
// 评分表单验证
const scoreRules = reactive({
  describe: [{ required: true, message: "评价不能为空", trigger: "blur" }],
  num: [{ required: true, message: "评分不能为空", trigger: "blur" }],
});

// 点击项目卡片 (++++++++++++++++++++++++++++++++++++++++++++++++++++++++)
const cardVisible = ref(false);
const cardTitle = ref("XXXXX项目");
const cardRef = ref();
const logFlag = ref(1); // 1项目进度 || 2项目日志
const cardInfo = reactive({
  projectName: "", // 名称
  projectContent: "", // 描述
  fileUrl: "", // 附件
  organize: "", // 主办单位
  sposonerName: "", // 主办人
  coOrganizeCopy: "", // 协办单位去重展示用
  coOrganize: "", // 协办单位
  coSposonerName: "", // 协办人
  projectFrom: "", // 项目来源
  projectLevel: "", // 项目等级
  progress: "", // 进度
  startTime: "", // 进度
  endTime: "", // 进度
  leaderName: "", // 分管领导
  scorerName: "", // 评分人
  scorer: "", // 评分人对应id
});

// 更新进度 （00000000000000000000000000000000000000000000000000000）
const updateVisible = ref(false);
const updateRef = ref();
const updateRuleForm = reactive({
  remark: "", // 备注
  fileUrl: "", // 附件
  id: "",
});
const fileListAttachment = ref([]); // 更新进度附件
// 更新进度验证
const updateRules = reactive({
  remark: [{ required: true, message: "备注不能为空", trigger: "blur" }],
  fileUrl: [{ required: true, message: "附件不能为空", trigger: "blur" }],
});

// 预览Pdf （++++++++++++++++++++++++++++++++++++++++++++++++++++++++）
const previewPdfVisible = ref(false);
const previewPdfUrl = ref(); // pdf地址
const pdfFlag = ref(1); // word文档地址 1、pdf 2、word 3、图片

const handleClick = (val) => {
  // console.log(val);
  activeName.value = val;
  searchInput.projectName= null // 项目名称
  searchInput.projectFrom= null // 项目来源
  searchInput.projectLevel= null // 项目等级
  searchInput.state= null //
  searchInput.organize= null // 主办单位
  searchInput.sposonerName= null // 主办人
  searchInput.coOrganize= null // 协办单位
  searchInput.coSposonerName= null // 协办人
  searchInput.createTime= null // 创建时间
  searchInput.periodTime= null // 周期时间
  searchInput.finishTime= null // 完成时间
  searchInput.scoreState= null // 是否已评分：1已评分，0未评分，null全部
  searchInput.collect= null //    是否已关注，1收藏，0未收藏，null全部
  searchInput.hasTask= null //       是否有任务：1有任务，0没有任务，null全部
  searchInput.isScore= null //    是否我评分，1是我，0不是我，null全部
  searchBtn()
};

// 获取账户列表
const getList = async () => {
  loading.value = true;
  console.log(currentPage.value, "getList里面的页数");

  let params = {
    page: currentPage.value, // 当前页
    rows: pageSize.value, // 一页数据条数
  };
  let data = {
    type: activeName.value, // 1我关注的、2我收藏的、3我负责的、4我协办的、null
    project: {
      projectName: searchInput.projectName, // 项目名称
      projectFrom: searchInput.projectFrom, // 项目来源
      projectLevel: searchInput.projectLevel, // 项目等级
      state: searchInput.state, // 1、正常在办，2、预警在办，3、超时在办，4、正常办结，5、超时办结
      organize: searchInput.organize, // 主办单位-单选
      coOrganize: searchInput.coOrganize, // 协办单位-多选
      sposonerName: searchInput.sposonerName, // 主办人
      coSposonerName: searchInput.coSposonerName, // 协办人
      scoreState: searchInput.scoreState, // 是否已评分：1已评分，0未评分，null全部
      collect: searchInput.collect, // 是否已关注，1收藏，0未收藏，null全部
      hasTask: searchInput.hasTask, // 是否有任务：1有任务，0没有任务，null全部
      isScore: searchInput.isScore, // 是否我评分，1是我，0不是我，null全部
    },
    // "t1": null, // 创建开始时间
    // "t2": null, // 创建结束时间
    // "t3": "2024-12-01", // 周期开始时间
    // "t4": "2024-12-31", // 周期结束时间
    // "t5": null, // 完成开始时间
    // "t6": null // 完成结束时间
  };

  if (searchInput.createTime) {
    data.t1 = searchInput.createTime[0];
    data.t2 = searchInput.createTime[1];
  }
  if (searchInput.periodTime) {
    data.t3 = searchInput.periodTime[0];
    data.t4 = searchInput.periodTime[1];
  }
  if (searchInput.finishTime) {
    data.t5 = searchInput.finishTime[0];
    data.t6 = searchInput.finishTime[1];
  }
  if (activeName.value == 3 || activeName.value == 4) {
    searchInput.organize = null;
    searchInput.sposonerName = null;
    searchInput.coOrganize = null;
    searchInput.coSposonerName = null;
  }
  let res = await axios({
    method: "post",
    url: api.value + "/api/sysProject/queryPage",
    headers: {
      tokenP: sessionStorage.getItem("tokenP"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: params,
    data: data,
  });
  console.log(res, "项目分页数据");
  if (res.data.code == 200) {
    tableData.list = res.data.data.project.rows;
    cardInfo.progress = res.data.data.config[2].configValue * 100;
    total.value = res.data.data.project.total;
    totalPage.value = res.data.data.project.totalPage;

    loading.value = false;
  } else {
    window.location.href =
      "https://chtech.ncjti.edu.cn/kpi/template/api/sysUser/authorize";
    loading.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 部门数据
const departmentList = async () => {
  // let res = await axios({
  //   method: "post",
  //   url: api.value + "/api/Organize/query",
  //   headers: {
  //     tokenP: sessionStorage.getItem("tokenP"),
  //     user_head: sessionStorage.getItem("userhead"),
  //   },
  // });
  // console.log(res, "部门数据");
  // if (res.data.code == 200) {
  //   departmentData.value = res.data.data;
  // } else {
  //   ElMessage({
  //     type: "error",
  //     showClose: true,
  //     message: res.data.message,
  //     center: true,
  //   });
  // }

  let res = await axios({
    method: "post",
    url: api.value + "/api/sysUser/queryOwn",
    headers: {
      tokenP: sessionStorage.getItem("tokenP"),
      user_head: sessionStorage.getItem("userhead"),
    },
  });
  console.log(res, "部门数据");
  if (res.data.code == 200) {
    let arr = [];
    res.data.data.manageDepartment.split(",").forEach((i) => {
      arr.push({
        oname: i,
      });
    });
    departmentData.value = arr;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
// 搜索框主办单位  根据部门获取用户
const getUser1 = async (val) => {
  console.log(val);
  if (val) {
    searchInput.organize = val[0];
    searchInput.sposonerName = val[1] || null;
  } else {
    searchInput.organize = null;
    searchInput.sposonerName = null;
  }
  searchBtn()
};
// 搜索框协办单位  根据部门获取用户
const getUser2 = async (val) => {
  console.log(val);
  if (val) {
    searchInput.coOrganize = val[0];
    searchInput.coSposonerName = val[1] || null;
  } else {
    searchInput.coOrganize = null;
    searchInput.coSposonerName = null;
  }
  searchBtn()
};
// // 搜索框主办单位  根据部门获取用户
// const getUser1 = async (val) => {
//   searchInput.sposonerName = "";
//   if (searchInput.organize) {
//     let data = new FormData();
//     data.append("organize", searchInput.organize);
//     let res = await axios({
//       method: "post",
//       url: api.value + "/api/Organize/queryUser",
//       headers: {
//         tokenP: sessionStorage.getItem("tokenP"),
//         user_head: sessionStorage.getItem("userhead"),
//       },
//       data: data,
//     });
//     console.log(res, "用户管理数据");
//     if (res.data.code == 200) {
//       userData1.value = res.data.data;
//     } else {
//       ElMessage({
//         type: "error",
//         showClose: true,
//         message: res.data.message,
//         center: true,
//       });
//     }
//   } else {
//     userData1.value = [];
//     // searchInput.sposonerName = "";
//   }
// };
// // 搜索框协办单位  根据部门获取用户
// const getUser2 = async () => {
//   searchInput.coSposonerName = "";
//   if (searchInput.coOrganize) {
//     let data = new FormData();
//     data.append("organize", searchInput.coOrganize);
//     let res = await axios({
//       method: "post",
//       url: api.value + "/api/Organize/queryUser",
//       headers: {
//         tokenP: sessionStorage.getItem("tokenP"),
//         user_head: sessionStorage.getItem("userhead"),
//       },
//       data: data,
//     });
//     console.log(res, "用户管理数据");
//     if (res.data.code == 200) {
//       userData2.value = res.data.data;
//     } else {
//       ElMessage({
//         type: "error",
//         showClose: true,
//         message: res.data.message,
//         center: true,
//       });
//     }
//   } else {
//     userData2.value = [];
//     // searchInput.coSposonerName = "";
//   }
// };

// 协办人数据
const userList = async () => {
  let res = await axios({
    method: "post",
    url: api.value + "/api/sysUser/queryPage",
    headers: {
      tokenP: sessionStorage.getItem("tokenP"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: {
      page: 1,
      rows: 100,
    },
    data: {
      userName: "",
    },
  });
  console.log(res, "协办人数据");
  if (res.data.code == 200) {
    // userData.value = res.data.data.rows;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
// 新增项目和搜索框中的协办人数据
const users = async () => {
  let res = await axios({
    method: "post",
    url: api.value + "/api/sysProject/queryCoUsers",
    headers: {
      tokenP: sessionStorage.getItem("tokenP"),
      user_head: sessionStorage.getItem("userhead"),
    },
  });
  console.log(res, "主办协办人员");
  // let resData=res.data
  // console.log(resData);
  if (res.data.code == 200) {
    let resdata = res.data.data;
    resdata.forEach((i) => {
      if (!i.userList.length) {
        i.disabled = true;
      }
      i.userName = i.organize;
      i.id = i.organize;
    });
    organizeData.value = resdata;
    let resJSON = JSON.parse(JSON.stringify(resdata));
    resJSON.forEach((i) => {
      i.disabled = false;
    });
    searchOrganizeData.value = resJSON;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  currentPage.value = 1;
  totalPage.value = "";
  tableData.list = [];
  let filter = document.getElementById("filter");
  filter.scrollTop = 0;
  getList();
}, 300);

// 点击项目卡片 (++++++++++++++++++++++++++++++++++++++++++++++++++)
const projectCard = async (row) => {
  cardVisible.value = true;
  console.log(row);
  
  cardTitle.value = row.projectName;
  fileList.value = row.fileUrl;
  cardInfo.projectName = row.projectName;
  cardInfo.projectContent = row.projectContent;
  cardInfo.fileUrl = row.fileUrl.split(",");
  cardInfo.organize = row.organize;
  cardInfo.sposonerName = row.sposonerName;
  cardInfo.coSposonerName = row.coSposonerName;

  // 协办单位去重展示用
  let arrs=[]
  console.log(row.coOrganize.split(','));
  row.coOrganize.split(',').forEach(item=>{
    let flag=arrs.some(i=>{
      return i==item
    })
    if(!flag){
      arrs.push(item)
    }
  })
  cardInfo.coOrganizeCopy = arrs.join(',');

  cardInfo.coOrganize = row.coOrganize;
  console.log(cardInfo.coOrganize);
  cardInfo.projectFrom = row.projectFrom;
  cardInfo.projectLevel = row.projectLevel;
  cardInfo.startTime = row.startTime;
  cardInfo.endTime = row.endTime;
  cardInfo.leaderName = row.leaderName;
  cardInfo.scorer = row.scorer;
  cardInfo.scorerName = row.scorerName;
  taskRuleForm.projectId = row.id;
  console.log(row.coSposonerName, row.coSposoner);
  console.log(row.sposonerName, row.sposoner);
  let arr = [];
  if (row.coSposonerName) {
    row.coSposonerName.split(",").forEach((item, ind) => {
      arr.push({ name: item, id: row.coSposoner.split(",")[ind] });
    });
  }
  let flag = arr.some((i) => {
    // "判断协办人里面是否有负责人"
    return i.id == row.sposoner;
  });
  console.log(flag);
  if (!flag) {
    arr.unshift({ name: row.sposonerName, id: row.sposoner });
  }
  console.log(arr);
  taskLeader.value = arr;
  taskList();
};
// 任务进度
const taskList = async () => {
  let data = new FormData();
  data.append("projectId", taskRuleForm.projectId);
  let res = await axios({
    method: "post",
    url: api.value + "/api/sysTask/queryTaskByProject",
    headers: {
      tokenP: sessionStorage.getItem("tokenP"),
      user_head: sessionStorage.getItem("userhead"),
    },
    data: data,
  });
  if (res.data.code == 200) {
    console.log(res, "任务管理");
    taskData.value = res.data.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
// 任务日志
const logList = async () => {
  let data = new FormData();
  data.append("projectId", taskRuleForm.projectId);
  let res = await axios({
    method: "post",
    url: api.value + "/api/sysProject/queryLogs",
    headers: {
      tokenP: sessionStorage.getItem("tokenP"),
      user_head: sessionStorage.getItem("userhead"),
    },
    data: data,
  });
  if (res.data.code == 200) {
    console.log(res, "任务日志");
    logData.value = res.data.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
const cancelCard = () => {
  cardVisible.value = false;
  taskRuleForm.projectId = "";
};
// 项目进度 || 项目日志 切换
const logChange = (val) => {
  logFlag.value = val;
  if (logFlag.value == 1) {
    taskList();
  } else if (logFlag.value == 2) {
    logList();
  }
};
// 项目滚动加载
const projectScroll = async (event) => {
  // console.log(event, "priceTable.value.bodyWrapper");
  if (event) {
    let table = event.target;
    // if (currentPage.value==1) {
    //   table.scrollTop = 0;
    //   console.log("置顶到顶部");
    // }
    // console.log(table.scrollTop, "高度");

    let scrollTop = table.scrollTop;
    let scrollHeight = table.scrollHeight;
    let clientHeight = table.clientHeight;
    if (scrollTop + clientHeight == scrollHeight) {
      console.log("滚动到底部了");
      // // 判断数据是否加载完
      if (currentPage.value < totalPage.value) {
        // 滚动到底部页面加一
        currentPage.value++;
        console.log(totalPage.value, currentPage.value, "总页数、当前页");
        let params = {
          page: currentPage.value, // 当前页
          rows: pageSize.value, // 一页数据条数
        };
        let data = {
          type: activeName.value, // 1我关注的、2我收藏的、3我负责的、4我协办的、null
          project: {
            projectName: searchInput.projectName, // 项目名称
            projectFrom: searchInput.projectFrom, // 项目来源
            projectLevel: searchInput.projectLevel, // 项目等级
            state: searchInput.state, // 1、正常在办，2、预警在办，3、超时在办，4、正常办结，5、超时办结
            organize: searchInput.organize, // 主办单位-单选
            coOrganize: searchInput.coOrganize, // 协办单位-多选
            sposonerName: searchInput.sposonerName, // 主办人
            coSposonerName: searchInput.coSposonerName, // 协办人
            scoreState: searchInput.scoreState, // 是否已评分：1已评分，0未评分，null全部
            collect: searchInput.collect, // 是否已关注，1收藏，0未收藏，null全部
            hasTask: searchInput.hasTask, // 是否有任务：1有任务，0没有任务，null全部
            isScore: searchInput.isScore, // 是否我评分，1是我，0不是我，null全部
          },
          // "t1": null, // 创建开始时间
          // "t2": null, // 创建结束时间
          // "t3": "2024-12-01", // 周期开始时间
          // "t4": "2024-12-31", // 周期结束时间
          // "t5": null, // 完成开始时间
          // "t6": null // 完成结束时间
        };

        if (searchInput.createTime) {
          data.t1 = searchInput.createTime[0];
          data.t2 = searchInput.createTime[1];
        }
        if (searchInput.periodTime) {
          data.t3 = searchInput.periodTime[0];
          data.t4 = searchInput.periodTime[1];
        }
        if (searchInput.finishTime) {
          data.t5 = searchInput.finishTime[0];
          data.t6 = searchInput.finishTime[1];
        }
        if (activeName.value == 3 || activeName.value == 4) {
          searchInput.organize = null;
          searchInput.sposonerName = null;
          searchInput.coOrganize = null;
          searchInput.coSposonerName = null;
        }
        let res = await axios({
          method: "post",
          url: api.value + "/api/sysProject/queryPage",
          headers: {
            tokenP: sessionStorage.getItem("tokenP"),
            user_head: sessionStorage.getItem("userhead"),
          },
          params: params,
          data: data,
        });
        console.log(res, "项目分页数据");
        if (res.data.code == 200) {
          tableData.list = [...tableData.list, ...res.data.data.project.rows];
          // total.value = res.data.data.project.total;
          // totalPage.value = res.data.data.project.totalPage;
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        console.log(currentPage.value, "加载完毕");
      }
    }
  }
};
// 收藏项目
const collectClick = async (row) => {
  let data = new FormData();
  data.append("projectId", row.id);
  if (row.collect == 1) {
    data.append("state", 0);
  } else if (row.collect == 0) {
    data.append("state", 1);
  }
  let res = await axios({
    method: "post",
    url: api.value + "/api/sysProject/collect",
    headers: {
      tokenP: sessionStorage.getItem("tokenP"),
      user_head: sessionStorage.getItem("userhead"),
    },
    data: data,
  });
  console.log(res, "收藏");
  if (res.data.code == 200) {
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 新建项目 （-----------------------------------------------------------------）
const addProjectbtn = () => {
  projectVisible.value = true;
  projectTitle.value = "新建项目";
  fileList.value = [];
  projectRuleForm.projectName = "";
  projectRuleForm.projectContent = "";
  projectRuleForm.fileUrl = [];

  projectRuleForm.organize = "";
  projectRuleForm.sposoner = "";
  sposonerVal.value = "";

  projectRuleForm.coOrganize = "";
  projectRuleForm.coSposoner = "";
  coSposonerVal.value = "";

  projectRuleForm.projectFrom = "";
  projectRuleForm.projectLevel = "";
  projectRuleForm.id = "";
};
// 勾选主办人
const organizeChange = async (val) => {
  console.log(val);
  return new Promise(async (resolve) => {
    projectRuleForm.scorer = [];
    if (val) {
      projectRuleForm.organize = val[0];
      projectRuleForm.sposoner = val[1];

      let formData = new FormData();
      formData.append("organizes", projectRuleForm.organize);

      let res = await axios({
        method: "post",
        url: api.value + "/api/sysUser/queryScorer",
        headers: {
          tokenP: sessionStorage.getItem("tokenP"),
          user_head: sessionStorage.getItem("userhead"),
        },
        data: formData,
      });
      console.log(res, "评分人列表");
      if (res.data.code == 200) {
        scorerData.value = res.data.data;
        resolve("success");
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
      // let params = {
      //   page: 1, // 当前页
      //   rows: 1000, // 一页数据条数
      // };
      // let data = {
      //   manageDepartment: projectRuleForm.organize, // 部门
      // };
      // let res = await axios({
      //   method: "post",
      //   url: api.value + "/api/sysUser/queryPage",
      //   headers: {
      //     tokenP: sessionStorage.getItem("tokenP"),
      //     user_head: sessionStorage.getItem("userhead"),
      //   },
      //   params: params,
      //   data: data,
      // });
      // console.log(res, "评分人列表");
      // if (res.data.code == 200) {
      //   scorerData.value = res.data.data.rows;
      //   resolve("success");
      // } else {
      //   ElMessage({
      //     type: "error",
      //     showClose: true,
      //     message: res.data.message,
      //     center: true,
      //   });
      // }
    }
  });
};
// 勾选协办人
const coOrganizeChange = (val) => {
  console.log(val);
  if (val) {
    let arr = [];
    let jrr = [];
    val.forEach((i) => {
      arr.push(i[0]);
      jrr.push(i[1]);
    });
    projectRuleForm.coOrganize = arr.join(",");
    projectRuleForm.coSposoner = jrr.join(",");
    console.log(arr.join(","), jrr.join(","));
  }
};
//编辑项目
const editProject = async (row) => {
  projectVisible.value = true;
  projectTitle.value = "编辑项目";
  console.log(row);
  if (row.fileUrl) {
    fileList.value = row.fileUrl.split(",");
    projectRuleForm.fileUrl = row.fileUrl.split(",");
  } else {
    fileList.value = [];
    projectRuleForm.fileUrl = [];
  }
  projectRuleForm.projectName = row.projectName;
  projectRuleForm.projectContent = row.projectContent;

  projectRuleForm.organize = row.organize;
  projectRuleForm.sposoner = row.sposoner;
  console.log([row.organize, row.sposoner.toString()]);
  sposonerVal.value = [row.organize, Number(row.sposoner)];

  projectRuleForm.coSposoner = row.coSposoner;
  projectRuleForm.coOrganize = row.coOrganize;
  let arr = [];
  row.coOrganize.split(",").forEach((item, ind) => {
    console.log(item, ind);
    arr.push([item, Number(row.coSposoner.split(",")[ind])]);
  });
  coSposonerVal.value = arr;

  projectRuleForm.projectFrom = row.projectFrom;
  projectRuleForm.projectLevel = row.projectLevel;
  projectRuleForm.id = row.id;
  await organizeChange([projectRuleForm.organize, projectRuleForm.sposoner]);
  projectRuleForm.scorer = row.scorer.split(",");
  // organizeChange([projectRuleForm.organize, projectRuleForm.sposoner]).then(
  //   (res) => {
  //     console.log(scorerData.value,res);
  //     if (res == "success") {
  //       projectRuleForm.scorer = row.scorer.split(",");
  //     }
  //   }
  // );
};
// 确定新建项目
const confirmProject = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = "";
      let data = {
        projectName: projectRuleForm.projectName,
        projectFrom: projectRuleForm.projectFrom,
        projectLevel: projectRuleForm.projectLevel,
        projectContent: projectRuleForm.projectContent,
        fileUrl: projectRuleForm.fileUrl.join(","),
        organize: projectRuleForm.organize,
        sposoner: projectRuleForm.sposoner,
        coOrganize: projectRuleForm.coOrganize,
        coSposoner: projectRuleForm.coSposoner,
        scorer: projectRuleForm.scorer.join(","),
      };
      console.log(data);

      // // 判断是否有id存在，有则是修改账号
      if (projectRuleForm.id) {
        data.id = projectRuleForm.id;
        res = await axios({
          method: "post",
          url: api.value + "/api/sysProject/update",
          headers: {
            tokenP: sessionStorage.getItem("tokenP"),
            user_head: sessionStorage.getItem("userhead"),
          },
          data: data,
        });
      } else {
        res = await axios({
          method: "post",
          url: api.value + "/api/sysProject/add",
          headers: {
            tokenP: sessionStorage.getItem("tokenP"),
            user_head: sessionStorage.getItem("userhead"),
          },
          data: data,
        });
      }
      console.log(data, "添加参数");
      console.log(res, "新增项目数据");
      if (res.data.code == 200) {
        projectVisible.value = false;
        getList();
        projectRef.value.resetFields();
        ElMessage({
          type: "success",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
    }
  });
};
// 取消新建项目
const cancelProject = () => {
  projectVisible.value = false;
  projectRef.value.resetFields();
  fileList.value = [];
  projectRuleForm.projectName = "";
  projectRuleForm.projectContent = "";
  projectRuleForm.fileUrl = [];

  projectRuleForm.organize = "";
  projectRuleForm.sposoner = "";
  sposonerVal.value = "";

  projectRuleForm.coOrganize = "";
  projectRuleForm.coSposoner = "";
  coSposonerVal.value = "";

  projectRuleForm.projectFrom = "";
  projectRuleForm.projectLevel = "";
  projectRuleForm.id = "";
};

// 催办所有项目
const urgeProject = async () => {
  ElMessageBox.confirm("确定催办所有项目？", "提示!!!", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let ids = [];
      tableData.list.forEach((item) => {
        ids.push(item.id);
      });
      let data = new FormData();
      data.append("projectIds", ids);
      if (ids.length) {
        let res = await axios({
          method: "post",
          url: api.value + "/api/sysProject/urge",
          headers: {
            tokenP: sessionStorage.getItem("tokenP"),
            user_head: sessionStorage.getItem("userhead"),
          },
          data: data,
        });
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        ElMessage({
          type: "warning",
          showClose: true,
          message: "暂无需要催办的项目",
          center: true,
        });
      }
    })
    .catch(() => {});
};
// 催办单个项目
const urgeOneProject = async (row) => {
  ElMessageBox.confirm("确定催办此项目？", "提示!!!", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let data = new FormData();
      data.append("projectIds", row.id);
      let res = await axios({
        method: "post",
        url: api.value + "/api/sysProject/urge",
        headers: {
          tokenP: sessionStorage.getItem("tokenP"),
          user_head: sessionStorage.getItem("userhead"),
        },
        data: data,
      });
      if (res.data.code == 200) {
        getList();
        ElMessage({
          type: "success",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
    })
    .catch(() => {});
};

// 添加照片时往fileList列表中添加图片信息
const handleChange = async (file, fileLists) => {
  // console.log(file, "1111");
};
// 可以获取图片参数
const handleUpload = async (file) => {
  console.log(file.file.type);
  if (
    file.file.type == "image/jpeg" ||
    file.file.type == "image/jpg" ||
    file.file.type == "image/png" ||
    file.file.type == "application/pdf" ||
    file.file.type ==
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  ) {
    if (fileList.value.length >= 3) {
      ElMessage.warning("最多可上传3张附件!");
      return false;
    }

    let data = new FormData();
    data.set("file", file.file);
    let res = await axios({
      method: "post",
      url: api.value + "/api/sysFile/upload",
      headers: {
        tokenP: sessionStorage.getItem("tokenP"),
        user_head: sessionStorage.getItem("user_head"),
      },
      data: data,
    });
    console.log(res, "图片上传成功");
    if (res.data.code == 200) {
      fileList.value.push(res.data.data);
      projectRuleForm.fileUrl = fileList.value;
    } else {
      ElMessage({
        type: "error",
        showClose: true,
        message: res.data.message,
        center: true,
      });
    }
  } else {
    ElMessage.warning("附件仅支持'.jpeg'、'.png'、'.pdf'、'.docx'格式");
  }
};
// 删除文件
const delFiles = (val) => {
  fileList.value = fileList.value.filter((i) => {
    return i !== val;
  });
  projectRuleForm.fileUrl = fileList.value;
};

// 删除项目
const delProject = (row) => {
  console.log(row);
  console.log("删除项目");
  ElMessageBox.confirm(`确定要删除<${row.projectName}>项目吗？`, "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let data = new FormData();
      data.append("id", row.id);
      let res = await axios({
        method: "post",
        url: api.value + "/api/sysProject/del",
        headers: {
          tokenP: sessionStorage.getItem("tokenP"),
          user_head: sessionStorage.getItem("userhead"),
        },
        data: data,
      });
      if (res.data.code == 200) {
        getList();
        ElMessage({
          type: "success",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete canceled",
      });
    });
};

// 新建任务 （******************************************************************）
const addTaskbtn = () => {
  taskVisible.value = true;
  taskTitle.value = "新建任务";
  taskRuleForm.taskName = "";
  taskRuleForm.scoreStandard = "";
  taskRuleForm.fileUrl = [];
  fileListTask.value = [];
  taskRuleForm.scoreLimit = "";
  taskRuleForm.weight = "";
  taskRuleForm.remindTime = "";
  taskRuleForm.warnTime = "";
  taskRuleForm.header = "";
  taskRuleForm.periodTime = "";
  taskRuleForm.id = "";
};

// 任务预警和任务提醒时间限制
const selectTimes = ref(Date.now());
const handleDateChange = (value) => {
  if (value && value.split(' ') && value.split(' ').length > 0) {
    // 使用空格作为分隔符，将日期时间字符串拆分成数组
    const parts = value.split(' ');
    // 取数组的第一个元素（日期部分）
    const datePart = parts[0];
    // 将日期部分按照连字符 '-' 拆分成数组
    const dateParts = datePart.split('-');
    // 去除月份和日期中的前导零
    const year = dateParts[0];
    const month = parseInt(dateParts[1], 10); // 使用parseInt去除前导零
    const day = parseInt(dateParts[2], 10); // 使用parseInt去除前导零
 
    // 取数组的第二个元素（时间部分）
    const timePart = parts[1];
    // 将时间部分按照冒号 ':' 拆分成数组
    const timeParts = timePart.split(':');
    // 去除小时、分钟和秒中的前导零
    const hour = parseInt(timeParts[0], 10); // 使用parseInt去除前导零
    const minute = parseInt(timeParts[1], 10); // 使用parseInt去除前导零
    const second = parseInt(timeParts[2], 10); // 使用parseInt去除前导零
    // 实时保存选择时间
    selectTimes.value = new Date(`${year}-${month}-${day} ${hour}:${minute}:${second}`).getTime();
  }
};
// 禁用比当前时间小的日期
const disabledDateFn = (time) => {
  //比当前时间小的日期禁用（返回false则禁用）
  return time.getTime() < Date.now() - 24 * 3600 * 1000;
};
// 限制比当前时间小的小时
const disabledHours = () => {
  const a = [];
  if (new Date(selectTimes.value).getTime() > Date.now()) return a;
  for (let i = 0; i < 24; i++) {
    if (new Date().getHours() <= i) continue;
    a.push(i);
  }
  return a;
};
// 禁用比当前时间小的分钟
const disabledMinutes = () => {
  const a = [];
  if (new Date(selectTimes.value).getTime() > Date.now()) return a;
  for (let i = 0; i < 60; i++) {
    if (new Date().getMinutes() <= i) continue;
    a.push(i);
  }
  return a;
};
// 禁用比当前时间小的秒
const disabledSeconds = () => {
  const a = [];
  if (new Date(selectTimes.value).getTime() > Date.now()) return a;
  for (let i = 0; i < 60; i++) {
    if (new Date().getSeconds() <= i) continue;
    a.push(i);
  }
  return a;
};

// 确定任务
const confirmTask = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = "";
      let data = {
        taskName: taskRuleForm.taskName, // 任务名称
        projectId: taskRuleForm.projectId, // 项目ID
        scoreStandard: taskRuleForm.scoreStandard, // 评价标准
        fileUrl: taskRuleForm.fileUrl.join(","), // 附件
        scoreLimit: taskRuleForm.scoreLimit, // 评分上限
        weight: taskRuleForm.weight, // 权重
        remindTime: taskRuleForm.remindTime, // 提醒时间
        warnTime: taskRuleForm.warnTime, // 预警时间
        header: taskRuleForm.header, // 负责人
        startTime: taskRuleForm.periodTime[0], // 周期-起始时间
        endTime: taskRuleForm.periodTime[1], // 周期-结束时间
      };
      // 判断是否有id存在，有则是修改账号
      if (taskRuleForm.id) {
        data.id = taskRuleForm.id;
        res = await axios({
          method: "post",
          url: api.value + "/api/sysTask/update",
          headers: {
            tokenP: sessionStorage.getItem("tokenP"),
            user_head: sessionStorage.getItem("userhead"),
          },
          data: data,
        });
      } else {
        res = await axios({
          method: "post",
          url: api.value + "/api/sysTask/add",
          headers: {
            tokenP: sessionStorage.getItem("tokenP"),
            user_head: sessionStorage.getItem("userhead"),
          },
          data: data,
        });
      }

      if (res.data.code == 200) {
        taskVisible.value = false;
        taskList();
        getList();
        taskRef.value.resetFields();
        ElMessage({
          type: "success",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
    }
  });
};
// 取消任务
const cancelTask = () => {
  taskVisible.value = false;
  taskRef.value.resetFields();
  taskRuleForm.taskName = "";
  taskRuleForm.scoreStandard = "";
  taskRuleForm.fileUrl = [];
  fileListTask.value = [];
  taskRuleForm.scoreLimit = "";
  taskRuleForm.weight = "";
  taskRuleForm.remindTime = "";
  taskRuleForm.warnTime = "";
  taskRuleForm.header = "";
  taskRuleForm.periodTime = "";
  taskRuleForm.id = "";
};
//编辑任务
const editTask = (row) => {
  taskVisible.value = true;
  taskTitle.value = "编辑任务";
  taskRuleForm.taskName = row.taskName;
  taskRuleForm.scoreStandard = row.scoreStandard;
  if (row.fileUrl) {
    taskRuleForm.fileUrl = row.fileUrl.split(",");
    fileListTask.value = row.fileUrl.split(",");
  } else {
    taskRuleForm.fileUrl = [];
    fileListTask.value = [];
  }

  taskRuleForm.scoreLimit = row.scoreLimit;
  taskRuleForm.weight = row.weight;
  taskRuleForm.remindTime = row.remindTime;
  taskRuleForm.warnTime = row.warnTime;
  taskRuleForm.header = row.header;
  taskRuleForm.periodTime = [row.startTime, row.endTime];
  taskRuleForm.id = row.id;
};
// 删除任务
const delTask = async (row) => {
  let data = new FormData();
  data.append("id", row.id);
  let res = await axios({
    method: "post",
    url: api.value + "/api/sysTask/del",
    headers: {
      tokenP: sessionStorage.getItem("tokenP"),
      user_head: sessionStorage.getItem("userhead"),
    },
    data: data,
  });
  if (res.data.code == 200) {
    taskList();
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
// 催办任务
const urgeTask = async (row) => {
  let data = new FormData();
  data.append("taskId", row.id);
  let res = await axios({
    method: "post",
    url: api.value + "/api/sysTask/urge",
    headers: {
      tokenP: sessionStorage.getItem("tokenP"),
      user_head: sessionStorage.getItem("userhead"),
    },
    data: data,
  });
  if (res.data.code == 200) {
    taskList();
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 可以获取图片参数
const handleUploadTask = async (file) => {
  if (
    file.file.type == "image/jpeg" ||
    file.file.type == "image/jpg" ||
    file.file.type == "image/png" ||
    file.file.type == "application/pdf" ||
    file.file.type ==
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  ) {
    if (fileListTask.value.length >= 3) {
      ElMessage.warning("最多可上传3张附件!");
      return false;
    }

    let data = new FormData();
    data.set("file", file.file);
    let res = await axios({
      method: "post",
      url: api.value + "/api/sysFile/upload",
      headers: {
        tokenP: sessionStorage.getItem("tokenP"),
        user_head: sessionStorage.getItem("user_head"),
      },
      data: data,
    });
    console.log(res, "图片上传成功");
    if (res.data.code == 200) {
      fileListTask.value.push(res.data.data);
      taskRuleForm.fileUrl = fileListTask.value;
    } else {
      ElMessage({
        type: "error",
        showClose: true,
        message: res.data.message,
        center: true,
      });
    }
  } else {
    ElMessage.warning("附件仅支持'.jpeg'、'.png'、'.pdf'、'.docx'格式");
  }
};
// 删除文件
const delFilesTask = (val) => {
  fileListTask.value = fileListTask.value.filter((i) => {
    return i !== val;
  });
  taskRuleForm.fileUrl = fileListTask.value;
};

// 评分 (==========================================================)
const scoreProject = (row) => {
  scoreVisible.value = true;
  scoreRuleForm.describe = "";
  scoreRuleForm.num = "";
  taskRuleForm.projectId = row.id;
};
const scoreProjects=()=>{
  scoreVisible.value = true;
  scoreRuleForm.describe = "";
  scoreRuleForm.num = "";
}
// 判断当前分管领导是否在评分人中
const isScorer = (row) => {
  // console.log(row);
  if (row) {
    let userId = sessionStorage.getItem("id");
    let flag = row.scorer.split(",").some((i) => {
      return userId == i;
    });
    return flag;
  } else {
    let userId = sessionStorage.getItem("id");
    let flag = cardInfo.scorer.split(",").some((i) => {
      return userId == i;
    });
    return flag;
  }
};
// 确定评分
const confirmScore = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let data = new FormData();
      data.append("projectId", taskRuleForm.projectId);
      data.append("evaluate", scoreRuleForm.describe);
      data.append("score", scoreRuleForm.num);
      console.log(taskRuleForm.projectId);
      
      let res = await axios({
        method: "post",
        url: api.value + "/api/sysProject/evaluate",
        headers: {
          tokenP: sessionStorage.getItem("tokenP"),
          user_head: sessionStorage.getItem("userhead"),
        },
        data: data,
      });
      if (res.data.code == 200) {
        taskList()
        getList()
        scoreVisible.value = false;
        ElMessage({
          type: "success",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
    }
  });
};
// 取消评分
const cancelScore = () => {
  scoreVisible.value = false;
  scoreRef.value.resetFields();
};

// 更新进度 (00000000000000000000000000000000000000000000000000000000)
const updateTask = async (row) => {
  updateVisible.value = true;
  updateRuleForm.id = row.id;
  updateRuleForm.remark = "";
  updateRuleForm.fileUrl = [];
  fileListAttachment.value = [];
};
// 确定更新进度
const confirmUpdate = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let data = new FormData();
      data.append("taskId", updateRuleForm.id);
      data.append("finishRemark", updateRuleForm.remark);
      data.append("fileUrl", updateRuleForm.fileUrl.join(","));
      let res = await axios({
        method: "post",
        url: api.value + "/api/sysTask/submitTask",
        headers: {
          tokenP: sessionStorage.getItem("tokenP"),
          user_head: sessionStorage.getItem("userhead"),
        },
        data: data,
      });
      if (res.data.code == 200) {
        taskList();
        getList();
        updateVisible.value = false;
        ElMessage({
          type: "success",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
    }
  });
};
// 可以获取图片参数
const handleAttachment = async (file) => {
  if (
    file.file.type == "image/jpeg" ||
    file.file.type == "image/jpg" ||
    file.file.type == "image/png" ||
    file.file.type == "application/pdf" ||
    file.file.type ==
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  ) {
    if (fileListAttachment.value.length >= 3) {
      ElMessage.warning("最多可上传3张附件!");
      return false;
    }

    let data = new FormData();
    data.set("file", file.file);
    let res = await axios({
      method: "post",
      url: api.value + "/api/sysFile/upload",
      headers: {
        tokenP: sessionStorage.getItem("tokenP"),
        user_head: sessionStorage.getItem("user_head"),
      },
      data: data,
    });
    console.log(res, "图片上传成功");
    if (res.data.code == 200) {
      fileListAttachment.value.push(res.data.data);
      updateRuleForm.fileUrl = fileListAttachment.value;
    } else {
      ElMessage({
        type: "error",
        showClose: true,
        message: res.data.message,
        center: true,
      });
    }
  } else {
    ElMessage.warning("附件仅支持'.jpeg'、'.png'、'.pdf'、'.docx'格式");
  }
};
// 删除文件
const delAttachment = (val) => {
  fileListAttachment.value = fileListAttachment.value.filter((i) => {
    return i !== val;
  });
  updateRuleForm.fileUrl = fileListAttachment.value;
};
// 取消更新进度
const cancelUpdate = () => {
  updateVisible.value = false;
  updateRuleForm.id = "";
  updateRuleForm.remark = "";
  updateRuleForm.fileUrl = [];
  fileListAttachment.value = [];
  updateRef.value.resetFields();
};

// 判断PDF word 图片
const pdfChange = (url) => {
  // pdf
  if (url.includes(".pdf")) {
    pdfFlag.value = 1;
  }
  // word
  else if (url.includes(".docx")) {
    pdfFlag.value = 2;
  }
  // jpg jpeg png
  else if (
    url.includes(".jpg") ||
    url.includes(".jpeg") ||
    url.includes(".png")
  ) {
    pdfFlag.value = 3;
  }
  filePreviewPdf(url);
};
// 查看PDF
const filePreviewPdf = (url) => {
  console.log(url, "pdf地址信息");
  if (url) {
    previewPdfVisible.value = true;
    previewPdfUrl.value = url;
  } else {
    ElMessage({
      type: "warning",
      showClose: true,
      message: "未上传文件",
      center: true,
    });
  }
};
const cancelPreviewPdf = () => {
  previewPdfVisible.value = false;
  previewPdfUrl.value = "";
};

// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};
// 每页显示条数
const handleSizeChange = (value) => {
  console.log(value, "每页显示条数");
  pageSize.value = value;
  getList();
};
// 分页
const handleCurrentChange = (value) => {
  console.log(value, "分页");
  currentPage.value = value;
  getList();
};

onBeforeMount(() => {
  api.value = store.state.user.api;
  userId.value = sessionStorage.getItem("id");
  projectScroll();
  departmentList();
  // userList();
  users();
});
onMounted(() => {
  const timer = setTimeout(() => {
    getList();
  }, 200);

  // clearTimeout(timer)
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.content-box {
  min-width: 1000px;
  width: calc(100vw - 260px);
  height: calc(100vh - 105px);
  margin: 20px auto;
  background-color: #fff;
  color: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: 0px 3px 10px rgba(0, 97, 255, 0.2);

  .left {
    // width: calc(100wh - 40px);
    display: flex;
    align-items: center;
    height: 60px;
    margin: 0 30px;
    border-bottom: 1px solid #ccc;
    color: #000;
    font-size: 18px;
    font-weight: 600;

    .cameratxt {
      display: block;
      height: 60px;
      line-height: 60px;
    }
  }

  .middle {
    width: calc(100% - 60px);
    margin: 0 auto;

    .el-tabs {
      :deep(.el-tabs__nav-wrap) {
        &::after {
          display: none;
        }

        .el-tabs__nav {
          .el-tabs__item {
            color: rgba(153, 153, 153, 1);
            margin-right: 30px;
          }

          .is-active {
            color: rgba(33, 107, 255, 1);
          }

          .el-tabs__active-bar {
            background-color: rgba(33, 107, 255, 1);
          }
        }
      }

      :deep(.el-tabs__content) {
        display: none;
      }
    }
  }

  .filter {
    width: calc(100% - 60px);
    margin: 0 auto 20px;
    flex: 1;
    overflow: auto;
    // 整个滚动条
    &::-webkit-scrollbar-track {
      background-color: #daeeff;
    }
    // 滚动条的滚动区域（轨道）
    &::-webkit-scrollbar {
      background-color: #0888f8;
      height: 3px;
      width: 5px;
    }
    &::-webkit-scrollbar-thumb:hover {
      cursor: pointer;
    }

    .condition {
      display: flex;
      flex-wrap: wrap;
      margin: 0 0 5px;

      .fil {
        color: #000;
        margin: 0 20px 10px 0;

        .search {
          background: linear-gradient(
            90deg,
            rgba(33, 107, 255, 1) 0%,
            rgba(102, 182, 255, 1) 100%
          );
        }
      }
    }

    .project {
      display: flex;
      flex-wrap: wrap;

      .el-card {
        width: 370px;
        height: 235px;
        margin: 0 20px 20px 0;
        opacity: 1;
        border-radius: 4px;
        background: rgba(245, 248, 255, 1);
        box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.05);

        .title {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .name {
            display: flex;
            align-items: center;

            // width: 125px;
            .projectName {
              font-weight: 600;
              max-width: 80px;
              overflow: hidden;
              /* 确保超出的文本被裁剪 */
              white-space: nowrap;
              /* 确保文本在一行内显示 */
              text-overflow: ellipsis;
              /* 使用省略号表示文本被裁剪 */
            }

            .shewai {
              margin-left: 5px;
              padding: 0 2px;
              font-size: 12px;
              border-radius: 2px;
              border: 1px solid rgba(33, 107, 255, 1);
              color: rgba(33, 107, 255, 1);
            }

            // .jinji {
            //   margin-left: 5px;
            //   padding: 0 2px;
            //   font-size: 12px;
            //   border-radius: 2px;
            //   border: 1px solid rgba(212, 48, 48, 1);
            //   color: rgba(212, 48, 48, 1);
            //   background-color: rgba(212, 48, 48, 0.2);
            // }
          }

          .btn {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .jinji {
              padding: 3px 11px;
              background-color: rgba(212, 48, 48, 1);
              color: #fff;
              font-size: 12px;
              margin-right: 12px;
              border-radius: 3px;
            }
            .el-button {
              color: #fff;
            }

            .el-dropdown {
              margin-left: 12px;
            }
          }
        }

        .info {
          font-size: 12px;

          .item:nth-child(1) {
            margin-top: 4px;
          }

          .item {
            margin-bottom: 4px;
          }

          .plan {
            display: flex;
            align-items: center;
            :deep(.el-progress-bar) {
              width: 180px;
            }

            img {
              width: 20px;
              height: 20px;
              cursor: pointer;
              transform: translateY(-2px);
            }
          }

          .score {
            color: blueviolet;
            font-size: 18px;
          }
        }
      }
    }
  }

  // 项目新增样式
  :deep(.project) {
    // height: 300px;
    border-radius: 11px;

    .el-dialog__header {
      border-radius: 11px 11px 0 0;
      background: rgba(237, 241, 245, 1);
      font-weight: 600;
      margin: 0;
      height: 32px;

      .el-dialog__headerbtn {
        outline: none;
      }
    }

    .el-dialog__body {
      padding: 30px 30px 0 30px;

      .el-form {
        .el-form-item {
          .el-input {
            width: 460px;

            .el-input-group__append {
              // padding: 0;
            }
          }

          .el-textarea {
            width: 460px;
          }

          .avatar-uploader {
            .el-upload-list {
              display: none;
            }
          }

          .fileList {
            .files {
              padding: 0 5px;
              display: flex;
              align-items: center;

              .el-icon {
                cursor: pointer;
                margin-left: 8px;
              }

              .el-icon:hover {
                color: red;
              }
            }

            .files:hover {
              background-color: rgb(245, 247, 250);
            }
          }
        }

        .resetPassword {
          color: rgba(43, 151, 252, 1);
          padding-left: 40px;
          display: inline-block;
          margin-bottom: 15px;
        }

        .options {
          margin: 60px 0 40px 0;

          .el-form-item__content {
            display: flex;
            flex-direction: row-reverse;

            .queding {
              margin-left: 20px;
              background: linear-gradient(
                90deg,
                rgba(33, 107, 255, 1) 0%,
                rgba(102, 182, 255, 1) 100%
              );
              border: none;
            }

            .quxiao {
              border: 1px solid rgba(43, 151, 252, 1);
              color: rgba(43, 151, 252, 1);
            }
          }
        }
      }
    }
  }

  // 点击卡片弹窗
  :deep(.projectCard) {
    // width: 1400px;
    border-radius: 11px;

    .el-dialog__header {
      border-radius: 11px 11px 0 0;
      background: rgba(237, 241, 245, 1);
      font-weight: 600;
      margin: 0;
      height: 32px;

      .el-dialog__headerbtn {
        outline: none;
      }
    }

    .el-dialog__body {
      padding: 20px 30px 0 30px;
      height: 700px;
      overflow: auto;

      .title {
        margin-bottom: 15px;
        font-size: 16px;
        font-weight: 600;
        color: rgba(3, 3, 2, 1);
        letter-spacing: 1px;
      }

      .info {
        font-size: 14px;
        color: rgba(128, 128, 128, 1);
        letter-spacing: 1px;
        text-indent: 2em;
        /* 设置段落首行缩进2em */
      }

      .unit {
        display: flex;
        flex-wrap: wrap;

        .unit_i {
          font-size: 14px;
          margin-right: 25px;
          letter-spacing: 1px;

          .key {
            color: #000;
            font-weight: 500;
            margin-right: 3px;
          }

          .value {
            color: rgba(128, 128, 128, 1);
          }

          .attachment {
            color: rgba(33, 107, 255, 1);
            cursor: pointer;
          }
        }
      }

      .participation {
        margin-bottom: 15px;

        .el-button {
          opacity: 1;
          border-radius: 8px;
          background: rgba(166, 166, 166, 0.1);
          color: rgba(166, 166, 166, 1);
          border: 1px solid rgba(166, 166, 166, 1);
        }

        .active {
          opacity: 1;
          border-radius: 8px;
          background: rgba(0, 97, 255, 0.1);
          color: rgba(0, 97, 255, 1);
          border: 1px solid rgba(0, 97, 255, 1);
        }
      }

      .schedule {
        width: 100%;
        height: 40px;
        border-radius: 8px;
        background: rgba(0, 0, 0, 0.05);
        margin: 0 0 15px 0;
        line-height: 40px;

        span:nth-child(1) {
          margin: 0 0 0 15px;
          font-size: 20px;
          font-weight: 500;
          letter-spacing: 0px;
          color: rgba(0, 0, 0, 1);
        }

        span:nth-child(2) {
          letter-spacing: 0px;
          color: rgba(0, 97, 255, 1);
        }
      }

      .el-table--fit {
        // height: 400px;
        .el-table__header-wrapper {
          background-color: #000;
          font-size: 14px;
          color: #000;

          .cell {
            color: rgba(90, 96, 127, 1);
          }
        }

        .el-table__row {
          // height: 40px;
          font-size: 14px;
          color: #000;
        }

        .el-table__row td {
          // padding: 0;
          border: 0;
        }

        .el-button--primary {
          margin-left: 5px;
        }

        :deep(.el-table__body .even) {
          background-color: #fff;
        }

        :deep(.el-table__body .odd) {
          background-color: rgba(240, 243, 247, 1);
        }

        .options {
          display: flex;
          justify-content: center;
          align-items: center;

          .edit {
            margin-right: 15px;
            color: rgba(30, 125, 251, 1);
            cursor: pointer;
          }

          .look {
            color: rgba(212, 48, 48, 1);
            cursor: pointer;
          }

          .del {
            margin-right: 15px;
            color: rgba(212, 48, 48, 1);
            cursor: pointer;
          }
        }
      }

      .search {
        background: linear-gradient(
          90deg,
          rgba(33, 107, 255, 1) 0%,
          rgba(102, 182, 255, 1) 100%
        );
        margin: 15px 0;
      }
    }
  }
  // 预览文档样式
  :deep(.previewPdf) {
    // height: 500px;
    border-radius: 11px;

    .el-dialog__header {
      border-radius: 11px 11px 0 0;
      background: rgba(237, 241, 245, 1);
      font-weight: 600;
      margin: 0;
      height: 32px;

      .el-dialog__headerbtn {
        outline: none;
      }
    }

    .el-dialog__body {
      padding: 20px;
      height: 800px;
      overflow: auto;
      .pdfMain {
        width: 100%;
        height: 100%;
      }
      .home-box {
        width: 100%;
        height: 100%;
        .continer {
          height: 100%;
          img {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }
      }
    }
  }

  .el-pagination {
    width: calc(100vw - 300px);
    margin: 20px auto;
    justify-content: flex-end;

    :deep(.el-pagination__total) {
      color: #000;
    }

    :deep(.el-pagination__goto) {
      color: #000;
    }

    :deep(.el-pagination__classifier) {
      color: #000;
    }

    :deep(.el-input__wrapper) {
      // border: 1px solid rgba(0, 0, 0, 1);
      // border-radius: 5px;
      // box-shadow: none;
      width: 100px;
    }

    :deep(.el-pager li) {
      margin: 0 5px;
      border: 1px solid rgba(0, 0, 0, 1);
      border-radius: 5px;
      background-color: transparent;
    }

    :deep(.el-pager li.is-active) {
      // background-color: rgba(111, 182, 184, 1);
      color: rgba(0, 149, 255, 1);
      border: 1px solid rgba(0, 149, 255, 1);
    }

    :deep(.btn-prev) {
      margin-right: 5px;
      border: 1px solid rgba(0, 0, 0, 1);
      border-radius: 5px;
      background-color: transparent;
    }

    :deep(.btn-next) {
      margin-left: 5px;
      border: 1px solid rgba(0, 0, 0, 1);
      border-radius: 5px;
      background-color: transparent;
    }
  }
}

.el-input {
  width: 192px;
}
</style>
