<template>
  <el-container>
    <div v-if="showHeader === false" class="Layout_space_between" style="padding: 9px 0;border-bottom:1px solid rgba(242,243,246,1);">
      <div class="Layout_flex_start" style="width: 90%">
        <el-checkbox v-model="checkAlls" style="margin-left: 53px;" @change="toggleSelection" />
        <div style="margin: 0 8% 0 10px" class="startCheck"> 已选择 {{ selectedData.length }} 个</div>
        <div class="iterationCode" @click="dialogVisibleDelete = true"><img class="iterationImage" src="@/assets/建立档案@2x.png"> 移出迭代</div>
        <div style="margin: 0 5%" class="iterationCode"><img class="iterationImage" src="@/assets/建立档案@2x.png">
          <el-dropdown trigger="click" placement="bottom">
            <span class="iterationCode">
              变更迭代
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-input v-model="SearchIterationValue" style="margin: 0 10px 10px; width: 90%;" size="mini" placeholder="搜索迭代" suffix-icon="el-icon-search" @input="SearchIteration(SearchIterationValue)" />
              <div class="scroll" style="height: 200px;">
                <div v-for="item in searchResult" :key="item.code" class="Layout_space_between" style="margin: 10px;">
                  <el-tooltip :disabled="item.name && item.name.length < 19 ? true : false" effect="dark" :content="item.name" placement="bottom">
                    <div class="searchResult" @click="changeIteration(item)">{{ item.name | ellipsis(15) }}</div>
                  </el-tooltip>
                  <div
                    class="searchStatus"
                    :class="{
                      'statusName': item.statusName === '未开始',
                      'statusName1': item.statusName === '进行中',
                      'statusName2': item.statusName === '已完成',
                    }"
                  > {{ item.statusName }}</div>
                </div>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div v-if="false" class="iterationCode"><img class="iterationImage" src="@/assets/建立档案@2x.png">
          <el-dropdown trigger="click" placement="bottom">
            <span class="iterationCode">
              变更状态
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="item in requiredArray"
                :key="item.code"
                :label="item.msg"
                :value="item.code"
                :class="{
                  'color4': item.code === 0,
                  'color0': item.code === 1,
                  'color1': item.code === 3,
                  'color2': item.code === 5,
                  'color3': item.code === 9
                }"
                @click.native="iterationUpdateReqStatus(item, 1)"
              >{{ item.msg }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <div class="endCheck" @click="cancel">取消选择</div>
    </div>
    <el-table
      ref="topicTable"
      v-loading="loading"
      :data="RequirementSet"
      row-key="id"
      :expand-row-keys="expandArr"
      :show-header="showHeader"
      :header-cell-style="{ color: '#4A4A4A', fontSize: '14px', fontWeight: '550', background: '#F7F7F7', borderTop: '1px solid #eceef6' }"
      show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column width="35">
        <img style="display: inline-block; width: 8px; vertical-align: middle;" :src="image_role">
      </el-table-column>
      <el-table-column type="selection" min-width="40" align="center" />
      <el-table-column type="expand" width="40">
        <template slot="header">
          <div class="expand"><i v-show="!allChange" class="el-icon-plus" @click="expandAll(true)" /></div>
          <div class="expand"><i v-show="allChange" class="el-icon-minus" @click="expandAll(false)" /></div>
        </template>
        <template slot-scope="props">
          <iterationTable :id="props.row.id" :type-list="taskScheduleEvent" />
        </template>
      </el-table-column>
      <el-table-column label="优先级" min-width="80" align="center">
        <template v-slot="scope">
          <div align="center">
            <div
              class="iteration_back"
              :class="{
                'priority_color': scope.row.priority === 0,
                'priority_color1': scope.row.priority === 1,
                'priority_color2': scope.row.priority === 2,
                'priority_color3': scope.row.priority === 3,
                'priority_color4': scope.row.priority === 4,
                'priority_color5': scope.row.priority === 5,
                'priority_color6': scope.row.priority === 6
              }"
            >
              {{ scope.row.priorityName }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="需求名称" min-width="250" show-overflow-tooltip>
        <template v-slot="scope">
          <div class="table-project-name" @click="clickRequiredName(scope.row.id)">
            <span class="id">{{ scope.row.requirementDisplayId }} <img v-if="scope.row.type === 1" :src="extraUrgent" style="height: 17px;padding: 0 10px;"></span>
            <span class="public_Jump">{{ scope.row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="150" align="left">
        <template v-slot="scope">
          <el-select
            v-model="scope.row.status"
            :class="[
              {
                'bottom-i': scope.row.status <= 0 || scope.row.status >= 30,
                'bottom-u': scope.row.status === 10 || scope.row.status === 16,
                'bottom-y': scope.row.status === 20,
                'status_color': scope.row.status === 0,
                'status_color1': scope.row.status === 10 || scope.row.status === 16 || scope.row.status === 20 || scope.row.status === 30 || scope.row.status === 40 || scope.row.status === 100,
                'status_color2': scope.row.status === 150
              }
            ]"
            class="btnSize"
            size="mini"
            @change="iterationUpdateReqStatus(scope.row, 2)"
          >
            <el-option v-for="item in scope.row.availableStatusList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="PM" min-width="100" show-overflow-tooltip align="center">
        <template v-if="scope.row.pmMemberInfoResponse" slot-scope="scope">
          <span>{{ scope.row.pmMemberInfoResponse.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="需求方向" min-width="150" align="center" show-overflow-toolti>
        <template v-slot="scope">
          {{ scope.row.rqmtOrntNames }}
        </template>
      </el-table-column>
      <el-table-column label="跟版客户端" min-width="200" show-overflow-tooltip align="center">
        <template v-slot="scope">
          <span v-for="(item, index) in scope.row.referredClientTypeName" :key="index">{{ item }}</span>
        </template>
      </el-table-column>
      <el-table-column label="PRD链接" min-width="300" show-overflow-tooltip align="left">
        <template v-slot="scope">
          <a :href="scope.row.mrdUrl" style="color: #409EFF;" target="_blank">{{ scope.row.mrdUrl }}</a>
        </template>
      </el-table-column>
      <el-table-column label="交付日期" min-width="200" align="center">
        <template slot-scope="scope">{{ scope.row.optionsObject === null? '' :scope.row.optionsObject.endTime }}</template>
      </el-table-column>
      <el-table-column label="任务数量" min-width="100" align="center">
        <template slot-scope="scope">{{ scope.row.taskCount }}</template>
      </el-table-column>
      <el-table-column label="缺陷数量" min-width="100" align="center">
        <template slot-scope="scope">{{ scope.row.bugCount }}</template>
      </el-table-column>
    </el-table>
    <el-footer class="public_footer" />
    <!-- 移出迭代 dialog -->
    <iteration-delete :show.sync="dialogVisibleDelete" :selected-data="selectedData" @iteratioFilter="iteratioFilter" />
  </el-container>
</template>

<script>
import '@/styles/PublicStyle/index.scss'
import iterationDelete from '@/views/projectManage/iteration/components/delete.vue'
import iterationTable from '@/views/projectManage/iteration/components/iterationTable.vue'
import Sortable from 'sortablejs'
import { configShowTaskEnum } from '@/api/taskIndex'
import image_role from '@/assets/麻将@2x.png' // 表格移动
import { iterationList, iterationRequire, iterationOrder, iterationChangeIteration } from '@/api/iteration.js'
import { updateRequirementStatus } from '@/api/requirement.js'
import extraUrgent from '@/assets/extraUrgent.png'
export default {
  components: {
    iterationDelete,
    iterationTable
  },
  filters: {
    ellipsis(value, index) {
      if (!value) return ''
      if (value.length > index) {
        return value.slice(0, index) + '...'
      }
      return value
    }
  },
  data() {
    return {
      extraUrgent: extraUrgent, // 紧急图片
      allChange: false, // 是否全展开
      expandArr: [], // 展开行数组
      taskScheduleEvent: [], // 排期类型
      image_role: image_role, // 表格移动
      dialogVisibleDelete: false, // 移除迭代
      requiredArray: [], // 需求状态
      showHeader: true, // 是否显示表头
      checkAll: [],
      loading: true,
      searchResult: [], // 变更迭代下的数据
      SearchIterationValue: '',
      checkAlls: false,
      iterationId: Number(this.$route.query.id),
      selectedData: [], // 选中的数据
      RequirementSet: [], // 迭代下的需求
      iterationData: {}, //
      bizId: localStorage.getItem('bizId')
    }
  },

  created() {
    this.getTaskStatus()
  },
  mounted() {
    this.iteratioFilter()
    this.SearchIteration()
    this.rowDrop()
  },
  methods: {
    async iteratioFilter() {
      const list = iterationList({ id: this.iterationId, curIndex: 1, pageSize: 15, bizId: this.bizId })
      const requiredList = iterationRequire({ id: this.iterationId, curIndex: 1, pageSize: 50, bizId: this.bizId })
      // const requirementEnum = showRequirementEnum()
      const listRes = await list
      const listRequire = await requiredList
      // const requiredstatus = await requirementEnum
      this.iterationData = listRes.data.list[0]
      this.RequirementSet = listRequire.data.right.list
      // this.requiredArray = requiredList.data.right.list.availableStatusList
      this.checkAll = this.RequirementSet
      this.loading = false
    },

    async getTaskStatus() { // 获取任务状态列表
      const res = await configShowTaskEnum()
      if (res.code === 200) {
        this.taskScheduleEvent = res.data.taskScheduleEvent || []
      }
    },

    SearchIteration(e) { // 筛选change
      iterationList({ name: e, curIndex: 1, pageSize: 1000, bizId: this.bizId }).then(res => { // 调用查询迭代list
        this.searchResult = res.data.list
      })
    },

    iterationUpdateReqStatus(ele, key) { // 修改需求状态
      const data = { reqIds: [], newStatus: '' }
      if (key === 1) { // 批量修改
        this.selectedData.map(item => {
          data.reqIds.push(item.id)
        })
        data.newStatus = ele.code
      }
      if (key === 2) { // 单独修改
        data.reqIds.push(ele.id)
        data.newStatus = ele.status
      }
      const modifier = localStorage.getItem('username')
      updateRequirementStatus({ id: ele.id, status: ele.status, modifier: modifier }).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.iteratioFilter()
        } else {
          this.$message.warning(res.msg)
        }
      }
      )
      // iterationUpdateReqStatus(data).then(res => {
      //   if (res.code === 200) {
      //     this.$message.success(res.msg)
      //     this.iteratioFilter()
      //   } else {
      //     this.$message.warning(res.msg)
      //   }
      // })
    },

    clickRequiredName(e) { // 需求跳转
      this.$router.push({ name: '需求详情', query: { id: e }})
    },

    expandAll(isEx) { // 展开表格
      this.allChange = isEx
      isEx ? this.expandArr = this.RequirementSet.map(item => item.id) : this.expandArr = []
    },

    changeIteration(val) { // 变更迭代
      this.selectedData.map(item => {
        return delete item.pm
      })
      iterationChangeIteration({ newIterationId: val.id, requirementInfoRequests: this.selectedData }).then(res => {
        if (res.code === 200) {
          this.iteratioFilter()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    cancel() { // 取消选择
      this.$refs.topicTable.clearSelection()
    },

    toggleSelection(val) { // 全选（需求）
      if (val) {
        this.RequirementSet.forEach(row => {
          this.$refs.topicTable.toggleRowSelection(row, true)
        })
      } else {
        this.$refs.topicTable.clearSelection()
      }
    },

    handleSelectionChange(val) { // 单选（需求）
      val.length === 0 ? this.showHeader = true : this.showHeader = false
      this.selectedData = val
      val.length === this.RequirementSet.length ? this.checkAlls = true : this.checkAlls = false
    },
    // 行拖拽
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.RequirementSet.splice(oldIndex, 1)[0]
          _this.RequirementSet.splice(newIndex, 0, currRow)
          const obj = {
            id: []
          }
          _this.RequirementSet.map(item => {
            obj.id.push(item.id)
          })
          iterationOrder(obj.id, _this.iterationId).then(res => {
            if (res.code === 200) {
              _this.$message.success(res.msg)
              _this.iteratioFilter()
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.expand i {
  border:1px solid #DCDFE6;
  cursor: pointer;
}
/deep/ .el-table__expand-icon{
  font-size: 14px;
  .el-icon{
    margin: 0;
    transform: translate(-50%, -50%);
    border:1px solid #DCDFE6;
  }
}
/deep/ .el-table__expand-icon .el-icon-arrow-right::before{
  content: "\E6D9";
}
/deep/ .el-table__expand-icon--expanded .el-icon-arrow-right::before{
  content: "\E6D8";
}
/deep/ .el-table__expand-icon--expanded {
  transform: rotate(180deg);
}
/deep/ .el-table__expanded-cell {
  background-color: #FFFFFF;
  padding: 0;
}
/deep/ .el-table__expanded-cell:hover {
  background-color: #FFFFFF !important;
}

.el-header {
  padding: 20px;
}

.iteration_back {
  border-radius: 4px;
  width: 33px;
  color: #FFF;
}

.iterationImage {
  display: inline-block;
  width: 13.46px;
}

.iterationCode {
  font-size:14px;
  font-family:PingFang SC;
  font-weight:400;
  line-height:20px;
  color:rgba(51,51,51,1);
  opacity:1;
  cursor: pointer;
}

.endCheck {
  width:58px;
  font-size:14px;
  cursor: pointer;
  font-family:PingFang SC;
  font-weight:400;
  line-height:20px;
  color:rgba(68,68,68,1);
  opacity:1;
}

.startCheck {
  width:82px;
  font-size:14px;
  font-family:PingFangSC-Medium;
  line-height:20px;
  color:rgba(74,74,74,1);
  opacity:1;
}

.table-project-name {
  cursor: pointer;
  display: flex;
  justify-content: center;
  flex-direction: column;
  .id {
    color: #A7AEBC;
    font-size: 10px;
  }
}
>>>.btnSize .el-input--suffix .el-input__inner {
    padding-right: 10px;
    padding-left: 10px;
}
.bottom-i { width: 73px; }
.bottom-u { width: 100px; }
.bottom-y { width: 110px; }
</style>
