<template>
  <el-dialog
    v-model="showDialog"
    width="800"
    @close="close"
    :close-on-click-modal="false"
  >
    <template #header>
      <div class="full-width flex flex-center flex-justify-between">
        <h4>任务详情</h4>
      </div>
    </template>
    <div>
      <el-input
        v-model="form.title"
        maxlength="20"
        clearable
        :disabled="!canEdit"
        style="height: 50px"
        class="font-16 bold"
        placeholder="请输入任务名称(最大20个字符)"
      ></el-input>
      <div
        class="full-width flex flex-justify-between flex-center padding-top mt-10"
        @click="goProject"
        v-if="task && task.projectId"
      >
        <span class="flex-center flex-justify-start title"
          >所属项目：{{ task.projectName }}</span
        >
        <el-icon>
          <ArrowRight />
        </el-icon>
      </div>
      <div class="mt-20">
        <div class="flex flex-center flex-justify-start">
          <span class="mr-10 title flex flex-justify-start">状态:</span>
          <wt-tag
            :data="status"
            :status="form.taskStatus"
            @change="changeStatus($event, 1)"
            :disabled="isFinish"
          />
        </div>

        <div class="mt-20 flex flex-center flex-justify-start">
          <span class="mr-10 title flex flex-justify-start">优先级:</span>
          <wt-tag
            :data="level"
            :disabled="!canEdit"
            :status="form.level"
            @change="changeStatus($event, 2)"
          />
        </div>

        <div class="mt-20 flex flex-center flex-justify-start">
          <span class="mr-10 title flex flex-justify-start">时间:</span>
          <div class="flex flex-center">
            <el-date-picker
              v-model="form.startTime"
              type="date"
              :disabled="!canEdit"
              placeholder="设置开始日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
            <div class="ml-5 mr-5">至</div>
            <el-date-picker
              v-model="form.endTime"
              type="date"
              :disabled="!canEdit"
              placeholder="设置截止日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </div>
        </div>

        <div class="mt-20 flex lex-align-start flex-justify-start">
          <span class="mr-10 title flex flex-justify-start">标签:</span>
          <div>
            <wt-label
              @submit="handleTags"
              :ids="[form.tags, form.category]"
              :disabled="!canEdit"
            />
          </div>
        </div>
        <div
          class="mt-20 flex lex-align-start flex-justify-start"
          v-if="form && form.createUserName && form.createUserName.length > 0"
        >
          <span class="mr-10 title flex flex-justify-start">创建人:</span>
          <div class="tag">
            <div class="ml-5">{{ form.createUserName }}</div>
          </div>
        </div>
        <div class="mt-20 flex lex-align-start flex-justify-start">
          <span class="mr-10 title flex flex-justify-start">执行者:</span>
          <div>
            <tasker
              :data="executeUser === null ? [] : executeUser"
              :disabled="!canEdit"
              ref="tasker"
              @success="selected"
            />
          </div>
        </div>
        <div class="mt-20 flex flex-align-start flex-justify-start">
          <span class="mr-10 title flex flex-justify-start">备注:</span>
          <el-input
            type="textarea"
            :rows="5"
            v-model="form.remark"
            :disabled="!canEdit"
          ></el-input>
        </div>

        <div class="mt-20 flex flex-align-start flex-justify-start flex-col">
          <div class="flex flex-center flex-justify-start">
            <span class="mr-10 title flex flex-justify-start">关联附件:</span>
            <filepicker
              :project-id="projectId"
              @submit="selection"
              v-if="canEdit"
            />
          </div>
          <div class="flex flex-center flex-justify-start full-width mt-10">
            <div class="title mr-10"></div>
            <div>
              <div v-for="item in fileList" :key="item.id">
                <div class="flex flex-center flex-justify-start">
                  {{ item.title }}
                  <preview :id="item.fileId" :show-action="true" />
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="flex flex-justify-start full-width flex-col">
          <div class="mt-10 flex flex-align-start flex-justify-start">
            <span class="mr-10 title flex flex-justify-start">任务进展:</span>
            <el-input
              type="textarea"
              :rows="5"
              v-model="form.taskProcess"
              :disabled="isFinish"
            ></el-input>
          </div>
          <div class="flex flex-justify-start mt-10 full-width">
            <div class="title mr-10">成果文件:</div>
            <upload-office
              @success="uploadResult"
              :max="1"
              v-if="isFinish === false"
            />
          </div>
          <div class="full-width flex flex-justify-start flex-center">
            <div class="title mr-10" />
            <div>
              <div v-for="item in resultFiles" :key="item.id">
                <div class="flex flex-justify-start flex-center">
                  {{ item.fileVO.originalFileName }}
                  ({{ item.createUserName }})
                  <preview :id="item.fileVO.id" :show-action="true"></preview>
                  <el-button
                    text
                    type="primary"
                    v-if="isFinish === false"
                    @click="removeFile(item)"
                    >删除</el-button
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="flex flex-justify-end full-width">
        <el-button type="primary" plain @click="showDialog = false"
          >取 消
        </el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
      <move
        ref="move"
        :file-id="resultFiles.map(ele => ele.fileId).join(',')"
        :project-id="form.projectId"
        @on-success="moveSucc"
      />
    </div>
  </el-dialog>
</template>

<script>
import WtTag from '@/views/task/component/wt-tag.vue'
import Tasker from '@/views/task/component/tasker.vue'
import filepicker from '@/components/filepicker/index.vue'
import WtLabel from '@/views/task/component/wt-label.vue'
import { useStore } from '@/store/user.js'
import Preview from '@/views/resource/component/preview.vue'
import api from '@/api/index.js'
import uploadOffice from '@/components/upload-office/index.vue'
import move from '@/views/task/component/move.vue'

export default {
  /**
   * 任务添加、查看
   */
  computed: {
    api() {
      return api
    }
  },
  components: {
    Preview,
    WtLabel,
    Tasker,
    WtTag,
    filepicker,
    uploadOffice,
    move
  },
  props: {
    projectId: {
      type: String,
      default: ''
    },
    task: {
      type: Object,
      default: () => {
        return null
      }
    }
  },
  setup() {
    const user = useStore()
    return { user }
  },
  data() {
    return {
      isFinish: false,
      showDialog: false,
      fileList: [],
      loading: false,
      canEdit: true,
      executeUser: [],
      resultFiles: [],
      editResult: false,
      isMove: false,
      form: {
        title: '',
        taskStatus: 1,
        level: 1,
        remark: '',
        startTime: '',
        endTime: '',
        executeUser: '',
        tags: '',
        taskProcess: ''
      },
      status: [
        {
          title: '待确认',
          value: 1,
          color: '#D7D7D7',
          checked: true
        },
        {
          title: '进行中',
          value: 2,
          color: '#47A6EA',
          checked: false
        },
        {
          title: '已提交',
          value: 3,
          color: '#ECAB56',
          checked: false
        },
        {
          title: '已完成',
          value: 4,
          color: '#80B336',
          checked: false
        },
        {
          title: '已取消',
          value: 5,
          color: '#C72A29',
          checked: false
        }
      ],
      level: [
        {
          title: 'P1',
          value: 1,
          color: '#C72A29',
          checked: true
        },
        {
          title: 'P2',
          value: 2,
          color: '#E89D42',
          checked: false
        },
        {
          title: 'P3',
          value: 3,
          color: '#47A6EA',
          checked: false
        },
        {
          title: 'P4',
          value: 4,
          color: '#A0A0A0',
          checked: false
        }
      ]
    }
  },
  methods: {
    init() {
      this.form = this.task
      if (this.task.executeUsers !== undefined) {
        this.executeUser = [...this.task.executeUsers]
      }
      this.canEdit = this.form.createUser === this.user.info.userId
      if (this.task.taskStatus > 2) {
        this.canEdit = false
      }
      if (this.task.files !== undefined && this.task.files.length > 0) {
        this.fileList = this.task.files
      }
      this.resultFileInfo()
    },
    fetchIndex(list, key) {
      const index = list.findIndex(ele => ele.value === key)
      if (index > -1) {
        list.map(ele => {
          ele.checked = false
          return ele
        })
        list[index].checked = true
      }
      return list
    },
    /**
     *
     * @param type = 1 新增 2 查看
     */
    show(type) {
      if (type !== 1) {
        this.form = this.task
        if (this.task.taskStatus === 4 || this.task.taskStatus === 5) {
          this.isFinish = true
        }
        this.init(this.task)
      } else {
        this.form.taskStatus = 1
        this.form.level = 1
        this.canEdit = true
      }
      this.showDialog = true
    },
    /**
     * 获取成果文件info
     */
    resultFileInfo() {
      if (this.task.id !== undefined) {
        this.$api.task.taskFileInfo({ id: this.task.id }).then(res => {
          if (res.code === 200) {
            this.resultFiles = res.data
          }
        })
      }
    },
    changeStatus(res, type) {
      if (type === 1) {
        this.form.taskStatus = res.value
      } else {
        this.form.level = res.value
      }
    },
    submit() {
      if (this.form.taskStatus === 3 && this.resultFiles.length === 0) {
        this.$message.error('请上传成果文件')
        return
      } else {
        this.saveResultFile()
      }

      if (
        this.form.taskStatus === 4 &&
        this.isMove === false &&
        this.isFinish === false
      ) {
        // 已完成 需要转移文件
        this.$refs.move.showDialog()
        return
      }
      if (this.isFinish) {
        this.showDialog = false
        return
      }
      // 从项目详情，添加任务
      if (this.projectId !== undefined && this.projectId.length > 0) {
        this.form.projectId = this.projectId
      }
      this.form.relatedIds = this.fileList.map(ele => ele.id).join(',')
      this.$api.task.addTask(this.form).then(res => {
        this.showDialog = false
        if (res.code === 200) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
        this.$emit('success')
      })
    },
    saveResultFile() {
      if (this.editResult === false) {
        return
      }
      this.$api.task
        .taskFile({
          taskId: this.form.id,
          ids: this.resultFiles.map(ele => ele.id).join(',')
        })
        .then(res => {
          if (res.code === 200) {
            console.log(res)
          }
        })
    },
    selection(list, extra) {
      this.fileList = list.map(ele => {
        return ele
      })
    },
    selected(list) {
      this.form.executeUser = list.map(ele => ele.id).join(',')
    },
    handleTags(tags) {
      this.form.tags = tags.find(ele => ele.type === 'tags').id
      this.form.category = tags.find(ele => ele.type === 'category').id
    },
    /**
     * 成果文件上传成果
     * @param list
     */
    uploadResult(list) {
      this.editResult = true
      this.resultFiles = list.map(ele => {
        return {
          id: ele.id,
          fileVO: ele,
          createUserName: this.user.info.nickName
        }
      })
    },
    close() {
      this.form = {
        title: '',
        taskStatus: 1,
        level: 1,
        remark: '',
        startTime: '',
        endTime: '',
        executeUser: '',
        tags: '',
        taskProcess: ''
      }
      this.resultFiles.length = 0
      this.executeUser.length = 0
      this.fileList.length = 0
      this.showDialog = false
      this.editResult = false
      this.isMove = false
      this.isFinish = false
      this.$refs.tasker.reset()
    },
    /**
     * 文件移动成功
     */
    moveSucc() {
      this.isMove = true
    },
    removeFile(item) {
      console.log(item)
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        console.log(res)
        if (res === 'confirm') {
          this.$api.task.delTaskFile({ ids: item.id }).then(res => {
            if (res.code === 200) {
              this.resultFiles = this.resultFiles.filter(e => e.id !== item.id)
            }
          })
        }
      })
    },
    goProject() {
      const routeData = this.$router.resolve({
        path: '/project',
        query: { id: this.task.projectId }
      })
      window.open(routeData.href, '_blank')
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  min-width: 60px;
}

:deep(.el-input__wrapper) {
  box-shadow: none;
  font-weight: bold;
  font-size: 16px;
  background-color: #eeeeee;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: none;
  background-color: #eeeeee;
}

.tag {
  min-width: 60px;
  height: 20px;
  border-radius: 20px;
  background-color: #a3773d;
  padding: 2px 10px;
  margin: 0 5px;
  color: white;
}
</style>
