<template>
  <el-drawer
    class="sub-task-drawer"
    :visible.sync="visible"
    :with-header="false"
    size="50%"
    :modal="false"
    @close="close"
  >
    <el-container class="is-vertical">
      <section class="top-control">
        <div v-show="formData.parentId > 0" class="back">
          <el-tooltip class="item" effect="dark" content="返回上一级子任务" placement="top">
            <i class="el-icon-arrow-left" @click="backParent(formData.parentId)" />
          </el-tooltip>
        </div>
        <div class="bug-id-status">
          <span>SUBTASK-{{ formData.id }}</span>
          <el-dropdown placement="bottom" @command="updateStatus">
            <el-button size="small" plainclass="el-dropdown-link drop_down">
              {{ getStatus.msg }}
              <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown" align="center">
              <el-dropdown-item
                v-for="item in allStatus"
                :key="item.msg"
                :command="{value:item.code,label:item.msg}"
                :disabled="formData.status === item.code? true: false"
              >{{ item.msg }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="control">
            <span v-if="formData.level <= 2" @click="createChildren = true"><i class="el-icon-s-operation" />添加子任务</span>
            <span @click="toDetail()"><i class="el-icon-tickets" />查看详情</span>
            <span @click="deleteDialog = true"><i class="el-icon-delete" />删除</span>
            <span class="last"><i class="el-icon-close" @click="close()" /></span>
          </div>
        </div>
        <div class="bug-name-control">
          <el-input
            v-model="formData.name"
            type="textarea"
            autosize
            placeholder="请输入内容"
            maxlength="150"
            show-word-limit
            @change="changeArea('name')"
          />
        </div>
      </section>
      <section class="main-section">
        <div class="el-main-title">
          <div class="title-left-icon" />
          <div class="title-left-name">基础信息</div>
        </div>
        <div class="detail-info">
          <el-form :inline="true" :model="formData" class="demo-form-inline" label-position="left" label-width="100px">
            <el-form-item label="所属父任务："><span class="module">{{ formData.parentName }}</span></el-form-item>
            <el-form-item label="业务线："><span class="module">{{ formData.bizIdString }}</span></el-form-item>
          </el-form>
          <el-form :inline="true" :model="formData" class="demo-form-inline" label-position="left" label-width="100px">
            <el-form-item label="开始日期：">
              <el-date-picker
                v-model="formData.startTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy.MM.dd"
                size="medium"
                style="width: 100%"
                prefix-icon="null"
                @change="changeArea('startTime')"
              />
            </el-form-item>
            <el-form-item label="结束日期：">
              <el-date-picker
                v-model="formData.endTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy.MM.dd"
                size="medium"
                style="width: 100%"
                prefix-icon="null"
                @change="changeArea('endTime')"
              />
            </el-form-item>
          </el-form>
          <el-form :inline="true" :model="formData" class="demo-form-all" label-position="left" label-width="100px">
            <el-form-item label="任务进度：">
              <div class="process">
                <el-slider v-model.number="formData.process" @change="changeProgres" />
              </div>
            </el-form-item>
            <el-form-item>
              <el-input v-model.number="formData.process" class="input-process" @change="changeProgres">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </section>
      <section class="main-section main-desc">
        <div class="el-main-title">
          <div class="title-left-icon" />
          <div class="title-left-name">用户信息</div>
        </div>
        <div class="detail-info">
          <el-form :model="formData" class="demo-form-inline" label-position="left" label-width="100px">
            <el-form-item label="负责人：">
              <search-people :value.sync="formData.owner" :clearable="false" @change="changeArea('owner')" />
            </el-form-item>
            <el-form-item label="其他参与人：">
              <search-people :value.sync="formData.participants" :multiple="true" @change="changeArea('participants')" />
            </el-form-item>
          </el-form>
        </div>
      </section>
      <section class="main-section main-desc">
        <div class="el-main-title">
          <div class="title-left-icon" />
          <div class="title-left-name">描述</div>
        </div>
        <div>
          <text-area :id="'pro-descs'" :value.sync="formData.remark" :empty-text="'点击'" :input-button="'添加描述'" @change="changeArea('remark')" />
        </div>
      </section>
      <!-- 子任务列表 -->
      <section v-if="formData.level <= 2" class="main-section">
        <div class="el-main-title">
          <div class="title-left-icon" />
          <div class="title-left-name">
            子任务
          </div>
          <el-tooltip class="item" effect="dark" content="添加子任务" placement="top">
            <i class="el-icon-circle-plus child-add" @click="addChild()" />
          </el-tooltip>
        </div>
        <div class="children-list">
          <add-children-list
            ref="add-children-list"
            :list.sync="formData.childSubTaskInfos"
            :data="formData"
            :all-status="allStatus"
            @toDetail="toChild"
            @change="getById()"
          />
        </div>
      </section>
      <create-children v-if="createChildren" :visible.sync="createChildren" :data="formData" @change="getById()" />
      <change-status v-if="statusDialog" :show-dialog.sync="statusDialog" :data="noCompleteTask" @confirm="changeArea('status');statusDialog=false" @cancel="getById()" />
      <!-- 删除 -->
      <normal-dialog
        v-if="deleteDialog"
        :show-dialog.sync="deleteDialog"
        title="删除确认"
        width="45%"
        :is-default-close="false"
        buttom-type="danger"
        @confirm="subTaskDelete()"
        @cancel="deleteDialog = false"
      >
        <article>
          <div class="danger-img">
            <img :src="dangerImg">
          </div>
          <div class="danger-title">{{ formData.name }}及其所有子任务会被删除，此操作不可撤销，是否确定？</div>
        </article>
      </normal-dialog>
    </el-container>
    <!-- 概览 -->
  </el-drawer>
</template>
<script>
import { EncryptId } from '@/utils/crypto-js.js'
const _ = require('lodash')
import { getById, subTaskUpdate, showIterationEnum, subTaskDelete } from '@/api/taskChild'
import searchPeople from '@/components/select/searchPeople'
import textArea from '@/components/input/textArea'
import addChildrenList from './addChildrenList'
import createChildren from './createChildren'
import changeStatus from './changeStatus'
import normalDialog from '@/components/dialog/normalDialog'
import danger from '@/assets/感叹@2x.png'
export default {
  components: {
    searchPeople,
    textArea,
    addChildrenList,
    normalDialog,
    createChildren,
    changeStatus
  },
  props: {
    childId: {
      type: Number,
      default: NaN,
      required: true
    }
  },
  data() {
    return {
      dangerImg: danger,
      visible: true,
      formData: {}, // 详细信息
      userInformation: localStorage.getItem('username'),
      userNames: localStorage.getItem('realname'),
      deleteDialog: false, // 删除弹窗
      taskId: this.childId, // 任务id
      allStatus: [], // 任务所有状态
      createChildren: false, // 新建子任务
      statusDialog: false, // 状态弹框
      noCompleteTask: [] // 当前任务中未完成的子任务
    }
  },
  computed: {
    getStatus() {
      return this.allStatus.find(item => item.code === this.formData.status) || { msg: null }
    }
  },
  watch: {
    childId: {
      handler(newV) {
        this.taskId = newV
        this.getById()
      },
      immediate: true
    },
    'formData.process': {
      handler(newV) {
        const val = `${newV}`.replace(/[^\d\.\d]/g, '')
        this.formData.process = Number(val)
      }
    }
  },
  created() {
    this.$store.state.data.status = true
    this.getTaskStatus()
  },
  destroyed() {
    this.$store.state.data.status = false
  },
  methods: {
    inputProcess(val) { // 校验数字
      this.formData.process = val.replace(/[^\d\.\d]/g, '')
    },
    changeProgres: _.debounce(function() { // 修改进度
      this.changeArea('process')
    }, 1000),
    updateStatus(e) { // 变更状态
      this.formData.status = e.value
      if (this.formData.status === 20) {
        this.noCompleteTask = []
        this.findNoComplete(this.formData.childSubTaskInfos)
        this.noCompleteTask = this.noCompleteTask.filter(item => item.status !== 20)
        if (this.noCompleteTask.length > 0) {
          this.statusDialog = true
          return
        }
      }
      this.changeArea('status')
    },
    findNoComplete(arr) { // 查找未完成子任务
      arr.map(item => {
        this.noCompleteTask = this.noCompleteTask.concat(item)
        this.findNoComplete(item.childSubTaskInfos)
      })
    },
    async changeArea(e) { // area修改
      const params = {
        id: this.formData.id,
        taskId: this.formData.taskId,
        bizId: this.formData.bizId
      }
      if (e === 'name') {
        this.formData.name = this.formData.name.replace(/\s/g, '')
        if (this.formData.name === '') {
          this.getById()
          return
        }
      }
      if (e === 'participants') {
        params[e] = this.formData[e].join(',')
      } else {
        params[e] = this.formData[e]
      }
      const res = await subTaskUpdate(params)
      if (res.code === 200) {
        this.$message({ message: '修改成功', type: 'success', duration: 1000, offset: 150 })
        this.getById()
        this.$emit('change')
      }
    },
    async getTaskStatus() { // 获取任务状态列表
      const res = await showIterationEnum()
      res.code === 200 ? this.allStatus = res.data.subTaskStatus : this.allStatus = []
    },
    async getById() { // 获取任务详情
      const res = await getById(this.taskId)
      if (res.code === 200) {
        this.formData = res.data
        this.formData.participants = this.formData.participants ? this.formData.participants.split(',') : []
      }
    },
    async subTaskDelete() { // 删除任务
      const res = await subTaskDelete(this.formData.id)
      if (res.code === 200) {
        this.$message({ message: '删除成功', type: 'success', duration: 1000, offset: 150 })
        this.close()
      }
    },
    addChild() { // 添加子任务
      this.formData.childSubTaskInfos.push({
        parentId: this.formData.id,
        name: null,
        bizId: this.formData.bizId,
        endTime: null,
        owner: localStorage.getItem('username'),
        ownerObject: { phoneUrl: localStorage.getItem('UserAvatar') },
        status: 0,
        edit: true,
        newNode: true
      })
      this.$refs['add-children-list'].scroll(`childadd` + (this.formData.childSubTaskInfos.length - 1))
    },
    close() { // 关闭
      this.$emit('close')
    },
    toDetail() { // 前往详情页
      const bizId_id = EncryptId(`${this.bizId}_${this.formData.id}`)
      this.$router.push({ name: '子任务详情', query: { bizId_id: bizId_id }})
    },
    backParent(id) { // 返回父任务
      this.taskId = id
      this.getById()
    },
    toChild(id) { // 前往子任务
      this.taskId = id
      this.getById()
    }
  }
}
</script>
<style scoped lang="less">
@import '@/styles/detail-pages.less';
/deep/.el-button {
  cursor: pointer;
}
.sub-task-drawer {
  margin-top: 60px;
}
.el-main-title {
  border-bottom: 1px solid rgba(238,238,238,1);
  padding-bottom: 20px;
  margin-bottom: 5px !important;
}
.top-control {
	padding: 10px 30px 20px 30px;
  position: relative;
  .back {
    position: absolute;
    left: 10px;
    font-size: 18px;
    top: 13px;
    cursor: pointer;
  }
	.bug-id-status {
		font-size: 16px;
		color: #333333;
    font-weight: bold;
		display: flex;
		align-items: center;
		span {
			margin-right: 17px;
    }
    .control {
      font-weight: 400;
      margin-left: auto;
      font-size: 14px;
      color: #333333;
			span {
				cursor: pointer;
				margin-right: 20px;
			}
      .last{
        margin-right: 0;
      }
			i {
				margin-right: 6px;
			}
		}
	}
	.bug-name-control {
		margin-top: 5px;
    font-weight: bold;
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
    /deep/.el-textarea{
      .el-textarea__inner{
        border: 1px solid rgba(220,223,230,0);
        padding-left: 10px;
        color:#333333;
        font-size: 18px;
        padding: 5px 0;
        font-weight: bold;
        resize:none;
      }
      .el-input__count {
        display: none;
      }
    }
    /deep/.el-textarea:hover{
      .el-textarea__inner{
        border: 1px solid rgba(220,223,230,1);
        resize: vertical;
      }
      .el-input__count {
        display: block;
      }
    }
	}
	/deep/.el-button--small{
		padding: 9px 10px;
		border-radius: 5px;
	}
}
.main-section {
	.main-section();
	margin: 0;
	width: 100%;
  .require-plan {
    display: flex;
    align-items: center;
    span {
      margin-left: 20px;
      color: #E6A23C;
      font-size: 12px;
    }
  }
  .detail-info {
    padding: 0 34px 20px 34px;
    /deep/.el-input__inner{
      border: 1px solid rgba(220,223,230,0);
      padding-left: 10px;
    }
    /deep/.el-input__inner:hover{
      border: 1px solid rgba(220,223,230,1)
		}
    /deep/.is-focus .el-input__inner {
      border: 1px solid #409EFF;
    }
    /deep/.el-select{
      .el-input__suffix-inner {
        visibility: hidden;
      }
    }
    /deep/.el-select:hover{
      .el-input__suffix-inner {
        visibility: visible;
      }
    }
  }
  .demo-form-inline {
		.el-form-item {
			width: 48%;
      margin-right: 0;
      margin-bottom: 10px;
      /deep/.el-select{
        width: 100%;
      }
      /deep/.el-form-item__content {
        width: calc(100% - 100px);
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
    }
    .module {
      margin-left: 10px;
    }
  }
  .demo-form-all {
		.el-form-item {
			width: 30%;
      margin-right: 0;
      margin-bottom: 15px;
      /deep/.el-form-item__content {
        width: calc(100% - 100px);
      }
      /deep/.el-input__inner{
        border: 1px solid rgba(220,223,230,1);
        padding-left: 10px;
      }
      /deep/.el-input-group__append {
        padding: 0 10px;
      }
    }
    /deep/.el-slider__button-wrapper {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .process {
      padding-left: 15px;
    }
	}
	.input-process {
    width: 90px;
    margin-left: 10px;
  }
  .child-add {
    color:#409EFF;
    margin-left: 5px;
  }
  .children-list {
    min-height: 15vh;
  }
}
.danger-img {
  width: 100%;
  padding: 0 60px 50px 60px;
  margin-bottom: 50px;
  position: relative;
  img {
    height: 50px;
    width: 50px;
    position: absolute;
    left: 50%;
    transform: translate(-50%,0);
  }
}
.danger-title {
	text-align: center;
  padding: 0 80px 50px 80px;
}
</style>
<style>
.popper-control {
  min-width: 100px !important;
}
</style>
