<template>
  <normal-dialog
    :show-dialog.sync="show"
    :title="title"
    :is-default-close="false"
    :submit-button="isDeleteStatus?'我知道了，删除':'确定'"
    :buttom-type="isDeleteStatus?'danger':'primary'"
    width="55%"
    @confirm="confirmForm()"
    @cancel="cancel()"
  >
    <article v-if="!isDeleteStatus">
      <el-form ref="form" :model="form" :rules="form_rules" label-width="100px" :label-position="'left'">
        <el-form-item label="排期类型" prop="type">
          <el-select v-model="form.type" clearable placeholder="请选择" style="width: 100%" :disabled="disabled">
            <el-option v-for="item in taskScheduleEvent" :key="item.code" :label="item.msg" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="参与人员" prop="peopleList">
          <search-people :value.sync="form.peopleList" :multiple="true" style="width: 100%" :size="'medium'" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="排期" prop="dayList">
          <div v-show="form.dayList.length > 0 ">{{ schedule }}（用时<span class="blue">{{ detailDayList.length }}</span>天）</div>
          <div v-show="form.dayList.length <= 0 " class="empty-schedule">添加排期</div>
          <div v-if="!disabled" class="picker-hidden">
            <sel-date-picker :start-end.sync="form.dayList" :detail-day-list="detailDayList" @getDetailDay="getDetailDay" />
          </div>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.desc" autocomplete="off" placeholder="请输入问题描述内容..." :disabled="disabled" />
        </el-form-item>
        <el-form-item label="关联任务" prop="taskList">
          <el-select
            v-model="selectTask"
            filterable
            remote
            reserve-keyword
            placeholder="请输入任务名称或ID"
            :remote-method="remoteMethod"
            :loading="loading"
            style="width: 100%"
            :disabled="disabled"
            @change="tasksChange"
          >
            <el-option
              v-for="item in tasksOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="task-list-show">
        <div v-for="item in tasksDetailList" :key="'task'+item.id" class="task-list-item">
          <div v-if="item.taskIdSting" class="item-id">{{ item.taskIdSting }}</div>
          <div v-if="item.taskId" class="item-id">{{ item.taskId }}</div>
          <div class="item-name"><span>{{ item.name }}</span></div>
          <div class="item-qa">测试负责人：<span>{{ item.qaObject !== null?item.qaObject.name: '' }}</span></div>
          <div class="item-rd">开发负责人：<span>{{ item.rdObject !== null?item.rdObject.name: '' }}</span></div>
          <i class="el-icon-circle-close item-cancel" @click="cancelTask(item.id)" />
        </div>
      </div>
    </article>
    <article v-if="isDeleteStatus">
      <div class="danger-img">
        <img :src="dangerImg">
      </div>
      <div class="delete-title">
        执行删除后，所有关联任务下的此排期均会被删除，并无法恢复，请谨慎操作！
      </div>
      <div class="people-list-show">
        <p>参与人：</p>
        <span>{{ peopleObjectList.join('，') }}</span>
      </div>
      <div class="task-list-show">
        <p>关联任务：</p>
        <div v-for="item in tasksDetailList" :key="'task'+item.id" class="task-list-item">
          <div v-if="item.taskIdSting" class="item-id">{{ item.taskIdSting }}</div>
          <div v-if="item.taskId" class="item-id">{{ item.taskId }}</div>
          <div class="item-name"><span>{{ item.name }}</span></div>
          <div class="item-qa">测试负责人：<span>{{ item.qaObject !== null?item.qaObject.name: '' }}</span></div>
          <div class="item-rd">开发负责人：<span>{{ item.rdObject !== null?item.rdObject.name: '' }}</span></div>
        </div>
      </div>
    </article>
  </normal-dialog>
</template>
<script>
const _ = require('lodash')
import searchPeople from '@/components/select/searchPeople'
import normalDialog from '@/components/dialog/normalDialog'
import selDatePicker from '@/components/picker/SelDatePicker'
import { taskList } from '@/api/projectIndex'
import { taskList as allTaskList, configShowTaskEnum } from '@/api/taskIndex'
import { getSeprateDayInfo, scheduleCreate, scheduleGet, scheduleUpdate, scheduleDelete } from '@/api/projectViewDetails'
import danger from '@/assets/感叹@2x.png'
export default {
  components: {
    searchPeople,
    normalDialog,
    selDatePicker
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    title: {
      type: String,
      default: '新建排期',
      required: false
    },
    detailData: { // 详细日期
      type: Object,
      default: () => null,
      required: false
    },
    selectTaskList: { // 已选任务列表
      type: Array,
      default: () => [],
      required: false
    },
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    isDelete: {// 是否删除状态
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      dangerImg: danger,
      form_rules: {
        type: [{ required: true, message: '事件类型不能为空', trigger: 'blur' }],
        peopleList: [{ required: true, message: '参与人员不能为空', trigger: 'blur' }],
        dayList: [{ required: true, message: '排期不能为空', trigger: 'blur' }],
        taskList: [{ required: true, message: '关联任务不能为空', trigger: 'blur' }]
      },
      show: this.visible,
      isDeleteStatus: this.isDelete,
      taskScheduleEvent: [],
      form: {
        bizId: localStorage.getItem('bizId'),
        type: '',
        peopleList: [],
        taskList: [],
        desc: '',
        dayList: [] // 日期列表
      },
      detailDayList: [], // 详细的日期
      schedule: '',
      selectTask: null, // 选择的任务id
      tasksOptions: [], // 任务下拉选项
      tasksDetailList: [], // 已有任务项目
      loading: false,
      peopleObjectList: [] // 参与人
    }
  },
  watch: {
    visible: {
      handler(newV, old) {
        this.show = newV
      },
      immediate: true
    },
    detailData: {
      handler(newV, old) {
        if (newV) {
          this.getScheduleData(newV.id)
        }
      },
      immediate: true
    },
    selectTaskList: { // 已选择任务列表
      handler(newV, old) {
        if (newV && newV.length > 0) {
          this.tasksOptions = newV
          this.tasksDetailList = [...newV]
          this.form.taskList = newV.map(item => item.id)
        }
      },
      immediate: true
    },
    title(newV, oldV) {
      this.title = newV
    },
    isDelete: {
      handler(newV, old) {
        this.isDeleteStatus = newV
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getType()
    this.getNowTask()
  },
  methods: {
    async getScheduleData(id) { // 当有传入的详细信息的时候
      const res = await scheduleGet(id)
      let obj
      if (res.code === 200) {
        obj = res.data
      } else {
        return false
      }
      this.form = {
        id: obj.id,
        bizId: localStorage.getItem('bizId'),
        type: obj.type,
        peopleList: obj.peopleList || [],
        taskList: obj.taskObjectList.map(item => item.id),
        desc: obj.desc,
        dayList: [obj.dayList[0], obj.dayList[obj.dayList.length - 1]] // 日期列表
      }
      this.detailDayList = obj.dayList || []
      this.schedule = obj.seperateDaysNoHoliday
      this.tasksDetailList = obj.taskObjectList || []
      this.peopleObjectList = obj.peopleObjectList.map(item => item.name) || []
    },
    async getType() {
      const resEnum = await configShowTaskEnum()
      if (resEnum.code === 200) {
        this.taskScheduleEvent = resEnum.data.taskScheduleEvent
      }
    },
    async getNowTask() { // 获取当前项目下任务
      const res = await taskList({
        projectId: this.$route.query.id
      })
      if (res.code === 200) {
        this.tasksOptions = res.data
      }
    },
    async remoteMethod(query) { // 远程搜索任务
      this.loading = true
      const res = await allTaskList({
        bizId: Number(localStorage.getItem('bizId')),
        name: query
      })
      if (res.code === 200) {
        this.loading = false
        this.tasksOptions = res.data
      } else {
        this.loading = false
      }
    },
    tasksChange(id) { // 任务列表变动
      const isEx = this.tasksDetailList.find(item => item.id === id)
      if (isEx) {
        this.$message({ message: '任务已存在', type: 'warning', duration: 1000, offset: 150 })
        this.selectTask = null
        return false
      }
      const res = this.tasksOptions.find(item => {
        return item.id === id
      })
      this.tasksDetailList.push(res)
      this.form.taskList.push(res.id)
      this.selectTask = null
    },
    cancelTask(id) { // 删除单个关联任务
      if (this.disabled) {
        return false
      }
      this.tasksDetailList = this.tasksDetailList.filter(item => item.id !== id)
      this.form.taskList = this.form.taskList.filter(item => item !== id)
    },
    getDetailDay(e) { // 获取详细排期日期
      this.detailDayList = e
      this.getSeprateDayInfo(e)
    },
    async getSeprateDayInfo(dataArr) { // 获取选中时间中的工作日时间
      const res = await getSeprateDayInfo(dataArr)
      if (res.code === 200) {
        this.schedule = res.data.seperateDaysNoHoliday
      }
    },
    async scheduleCreate(params) { // 创建排期
      const res = await scheduleCreate(params)
      if (res.code === 200) {
        this.$message({ message: '添加成功', type: 'success', duration: 1000, offset: 150 })
        this.$emit('update')
        this.cancel()
      }
    },
    async scheduleUpdate(params) { // 更新排期
      const res = await scheduleUpdate(params)
      if (res.code === 200) {
        this.$message({ message: '更新成功', type: 'success', duration: 1000, offset: 150 })
        this.$emit('update')
        this.cancel()
      }
    },
    async scheduleDelete() { // 删除排期
      const res = await scheduleDelete(this.form.id)
      if (res.code === 200) {
        this.$message({ message: '删除成功', type: 'success', duration: 1000, offset: 150 })
        this.$emit('update')
        this.cancel()
      }
    },
    confirmForm() { // 确认提交表单
      if (this.isDeleteStatus) {
        this.scheduleDelete()
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const params = _.cloneDeep(this.form)
          params.dayList = this.detailDayList
          params.id ? this.scheduleUpdate(params) : this.scheduleCreate(params)
        }
      })
    },
    cancel() { // 关闭弹框
      this.show = false
      this.isDeleteStatus = false
      this.$emit('update:visible', this.show)
      this.$emit('update:isDelete', this.isDeleteStatus)
    }
  }
}
</script>
<style scoped lang="scss">
article {
  max-height: 60vh;
  overflow: scroll;
    .blue {
    color: #409EFF;
  }
}
>>>.el-form {
  padding: 0 156px 0 60px;
}
.picker-hidden {
  opacity: 0;
  position: absolute;
  top: 0;
}
.empty-schedule {
  color:rgba(51,51,51,0.45);
}
.task-list-show {
  width: 100%;
  padding: 0 60px;
  .task-list-item {
    width: 100%;
    display: flex;
    margin: 10px 0;
    .item-id {
      width: 15%;
    }
    .item-name {
      width: 40%;
    }
    .item-qa {
      width: 20%;
    }
    .item-rd {
      width: 20%;
    }
    .item-cancel {
      font-size: 20px;
    }
    div {
      overflow: hidden;
      text-overflow:ellipsis;
      white-space: nowrap;
    }
  }
}
.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);
  }
}
.delete-title {
  width: 100%;
  padding: 0 60px 100px 60px;
  color: #333B4A;
  font-size: 18px;
  text-align: center;
}
.people-list-show {
  width: 100%;
  padding: 0 60px 50px 60px;
  p {
    color: #666666;
    font-size: 14px;
    margin-bottom: 20px;
  }
  span {
    color: #333333;
  }
}
</style>
