<template>
  <div class="copy-task">
    <el-dialog :title="tit_Name" :visible.sync="dialogFormVisible" width="70%" :close-on-click-modal="false" :destroy-on-close="true">
      <div class="blueStripe" />
      <el-form ref="task_form" :model="task_form" :rules="task_rulesForm" label-position="left" label-width="130px">
        <el-form-item label="任务名称" prop="name" style="width: 100%">
          <el-input v-model="task_form.name" autocomplete="off" placeholder="请输入任务名称" />
        </el-form-item>
        <div style="display:flex;align-items: center;justify-content: space-between;">
          <el-form-item label="直接归属" prop="source">
            <el-radio-group v-model="task_form.source" @change="get_source(task_form.source)">
              <el-radio :label="1">不归属</el-radio>
              <el-radio :label="2">需求</el-radio>
              <el-radio :label="3">项目</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="ascription_demand" label="归属需求" prop="requireId">
            <el-select v-model="task_form.requireId" filterable clearable placeholder="请选择" style="width:20vw">
              <el-option v-for="item in demandList" :key="item.id" :label="item.name" :value="item.id" @click.native="tit_Name === '编辑任务' ? taskUpdateRequire(item.id, requirementIdList.taskId) : getRequireItem(item), $set(task_form, 'taskIdFromDpm', '')" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ascription_project" label="归属项目" prop="projectId">
            <el-select v-model="task_form.projectId" filterable clearable placeholder="请选择" style="width:20vw">
              <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </div>
        <div style="display:flex;align-items: center;justify-content: space-between;">
          <div>
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="task_form.priority" filterable placeholder="请选择" style="width:20vw">
                <el-option v-for="item in arr_priority" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="业务线" prop="bizId">
              <el-select v-model="task_form.bizId" :disabled="tit_Name === '编辑任务' || task_form.source !== 2" placeholder="请选择" style="width:100%" filterable @change="task_change_bizId(task_form.bizId)">
                <el-option-group v-for="group in bizList" :key="group.code" :label="group.name">
                  <el-option v-for="item in group.options" :key="item.code" :label="item.name" :value="item.code" />
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item label="开发负责人" class="form-item-normal-lable">
              <el-select v-model="task_form.rdOwner" filterable clearable remote placeholder="请输入姓名或邮箱前缀" :remote-method="remoteMethod" :loading="loading" style="width: 100%">
                <el-option v-for="item in options" :key="item.idap" :label="item.name" :value="test2(item, 0)">
                  <div style="display: flex;justify-content: start;">
                    <div style="min-width:100px;color: #8492a6; font-size: 13px; overflow:hidden">{{ item.deptName }}</div>
                    <div style="min-width:80px">{{ item.name }}</div>
                    <div style="min-width:100px;color: #8492a6; font-size: 13px; overflow:hidden">{{ item.idap }}</div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="是否免测" prop="notest">
              <el-radio-group v-model="task_form.notest">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="模块" prop="moduleIds" class="form-item-normal-lable">
              <el-cascader v-model="task_form.moduleIds" clearable collapse-tags :props="props" :options="business_platform_Modular" placeholder="请选择" style="width: 20vw" />
            </el-form-item>
            <el-form-item label="测试负责人" class="form-item-normal-lable">
              <el-select v-model="task_form.qaOwner" filterable clearable remote placeholder="请输入姓名或邮箱前缀" :remote-method="remoteMethod1" :loading="loading" style="width: 20vw">
                <el-option v-for="item in options1" :key="item.idap" :label="item.name" :value="test2(item, 0)">
                  <div style="display: flex;justify-content: start;">
                    <div style="min-width:100px;color: #8492a6; font-size: 13px; overflow:hidden">{{ item.deptName }}</div>
                    <div style="min-width:80px">{{ item.name }}</div>
                    <div style="min-width:100px;color: #8492a6; font-size: 13px; overflow:hidden">{{ item.idap }}</div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="技术文档链接" class="form-item-normal-lable">
          <el-input v-model="task_form.devUrl" placeholder="请粘贴链接" />
        </el-form-item>
        <div style="display:flex;align-items: center;justify-content: space-between;">
          <el-form-item label="是否跟版" prop="followVersion">
            <el-radio-group v-model="task_form.followVersion" @change="get_followVersion(task_form.followVersion)">
              <el-radio :label="2">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="show_Client" label="涉及的客户端" prop="involveApp">
            <el-select v-model="task_form.involveApp" filterable remote :loading="loading" clearable placeholder="请选择" style="width: 20vw">
              <el-option v-for="item in appClient" :key="item.code" :label="item.msg" :value="item.code" />
            </el-select>
          </el-form-item>
        </div>
        <div v-if="ascription_demand && show_schedule" style="color: #E81C1C; font-size: 12px; margin: 0 20px 10px;">
          <i class="el-icon-warning-outline" /> {{ tit_Name === '编辑任务' ? '您选择的任务归属需求来自望岳，该任务未设置关联的望岳任务，请进行设置，以便于后续排期的同步！' : '您选择的任务归属需求来自望岳，请设置该任务关联的望岳任务，以便于后期排期的同步！' }}
        </div>
        <el-form-item v-if="ascription_demand && show_schedule" clearable label="关联望岳的任务" prop="taskIdFromDpm">
          <el-select v-model="task_form.taskIdFromDpm" filterable placeholder="请选择" style="width: 100%">
            <el-option v-for="item in arr_schedule" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="tit_Name === '新建任务'" type="primary" @click="tit_Name === '新建任务'?throttleTask(task_form):uptate_task(task_form)">创 建</el-button>
        <el-button v-else type="primary" @click="tit_Name === '新建任务'?throttleTask(task_form):uptate_task(task_form)">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { analysisBizId_id, EncryptId } from '@/utils/crypto-js.js'
const _ = require('lodash')
import { taskCreate, memberQueryMemberInfoByIDAPorName, configShowTaskEnum, configShowRequirementVersionEnum, taskGet, taskUpdate, projectListProject, getRelDpmTask } from '@/api/taskIndex' // ajax
import { projectList, settingGetBizList, settingGetMyAndOtherBizList } from '@/api/projectIndex'
import { settingQueryBizModuleList } from '@/api/defectManage'
export default {
  props: {
    noJump: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      arr_priority: [{ value: 0, name: 'P0' }, { value: 1, name: 'P1' }, { value: 2, name: 'P2' }, { value: 3, name: 'P3' }],
      dialogFormVisible: false,
      task_form: {},
      props: { multiple: true },
      ascription_project: false, // 归属项目（隐藏）
      ascription_demand: false, // 归属需求（隐藏）
      test: {},
      bizList: [],
      loading: false,
      tit: '', // 跳转
      tit_Name: '', // 新建（编辑）
      projectId: -1, // 项目id
      requireId: -1, // 需求id
      options: [], // 员工信息
      options1: [],
      noTest: [], // 是否免测
      all_bizId: [], // 业务线
      appClient: [], // 涉及业务线
      arr_Modular: [], // 模块数据‘
      business_platform_Modular: [], // 模块
      show_Client: false, // 涉及的客户端（显示）
      projectList: [], // 归属项目数据
      demandList: [], // 需求list
      arr_schedule: [], // 关联望岳的任务list
      show_schedule: false,
      userInformation: localStorage.getItem('username'),
      userNames: localStorage.getItem('realname'),
      requirementIdList: {},
      task_rulesForm: {
        name: [{ required: true, message: '请输入任务名称', trigger: 'change' }],
        priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
        bizId: [{ required: true, message: '请选择业务线', trigger: 'change' }],
        source: [{ required: true, message: '请输入直接归属', trigger: 'change' }],
        requireId: [{ required: true, message: '请选择归属需求', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择归属项目', trigger: 'change' }],
        followVersion: [{ required: true, message: '请选择是否跟版', trigger: 'blur' }],
        notest: [{ required: true, message: '请选择是否免测', trigger: 'blur' }],
        cliType: [{ required: true, message: '请选择业务/平台/模块', trigger: 'blur' }],
        involveApp: [{ required: true, message: '请选择涉及的客户端', trigger: 'blur' }],
        taskIdFromDpm: [{ required: true, message: '请选择关联望岳的任务', trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapGetters(['bizId'])
  },
  created() {
    this.analysisBizId_id()
    this.settingGetBizList()
  },
  mounted() {
    this.get_taskSelect()
    this.bugDataGet(this.bizId)
  },
  methods: {
    analysisBizId_id() { // 解析路由中的bizId_id
      if (!this.$route.query.bizId_id) return
      const bizId_id = analysisBizId_id(this.$route.query.bizId_id)
      this.projectId = bizId_id[1]
      this.requireId = bizId_id[1]
    },
    async init(e, id, data = null) {
      this.tit_Name = '新建任务'
      switch (e) {
        case 1: // 新建任务（任务主页）
          this.dialogFormVisible = true
          this.ascription_demand = false
          this.ascription_project = false
          this.task_form = { 'notest': 0, 'followVersion': 2, 'source': 1, 'bizId': this.bizId }
          this.requirementIdList = { 'name': '主页', 'data': null }
          this.show_Client = false
          this.$nextTick(() => {
            this.$refs['task_form'].clearValidate()
          })
          this.task_change_bizId(this.bizId)
          break
        case 2: // 新建任务（项目详情）
          this.tit = '新建任务'
          projectList({ id: this.projectId, curIndex: 1, pageSize: 15 }).then(res => {
            this.dialogFormVisible = true
            this.task_form = { 'followVersion': 2, 'notest': 0, 'source': 3, 'projectId': res.data[0].id, 'requireId': res.data[0].id, 'bizId': this.bizId }
            this.requirementIdList = { 'name': '项目', 'data': res.data[0].id }
            this.ascription_demand = false
            this.ascription_project = true
            this.show_Client = false
            this.task_change_bizId(this.bizId)
          })
          break
        case 3: // 编辑任务（任务详情）
          if (id[0].type === 'copy') {
            this.tit_Name = '新建任务'
          } else {
            this.tit_Name = '编辑任务'
          }
          taskGet(id[1]).then(res => {
            this.requirementIdList = { 'name': '需求', 'data': res.data.requireId, taskId: res.data.id }
            this.dialogFormVisible = true
            var that = this
            setTimeout(function() {
              that.task_form = {}
              that.task_form = res.data
              that.task_form.source === 3 ? that.ascription_project = true : that.ascription_project = false
              that.task_form.source === 2 ? that.ascription_demand = true : that.ascription_demand = false
              that.task_form.source === 1 ? that.ascription_demand = false : ''
              that.task_form.source === 1 ? that.ascription_project = false : ''
              that.task_form.followVersion === 2 ? that.show_Client = false : that.show_Client = true
              that.task_form.followVersion === 1 ? that.show_Client = true : that.show_Client = false
              that.task_form.cliType = [res.data.bizId, res.data.type, res.data.clientType]
              that.task_form.involveApp = Number(res.data.involveApp)
              if (id[0].type === 'copy') { that.$set(that.task_form, 'name', `复制从 ${id[0].name} `) }
              const arr_object = []
              arr_object.push(res.data.rdObject)
              arr_object.push(res.data.qaObject)
              var hash = {}
              that.options = arr_object.reduce(function(item, next) {
                hash[next.idap] ? '' : hash[next.idap] = true && item.push(next)
                return item
              }, [])
              that.options1 = arr_object.reduce(function(item, next) {
                hash[next.idap] ? '' : hash[next.idap] = true && item.push(next)
                return item
              }, [])
            }, 100)
            this.task_change_bizId(res.data.bizId, res.data.id)
            this.taskUpdateRequire(res.data.requireId, res.data.id)
          })
          break
        case 4: // 新建任务（需求详情）
          this.tit = '新建任务'
          var ss = {}
          configShowRequirementVersionEnum({ bizId: this.bizId }).then(res => {
            res.data.map(item => {
              item.id === this.requireId ? ss = item : ''
            })
            this.dialogFormVisible = true
            this.ascription_demand = true
            this.ascription_project = false
            this.task_form = { 'followVersion': 2, 'notest': 0, 'source': 2, 'projectId': '', 'requireId': ss.id, 'bizId': this.bizId }
            this.show_Client = false
            if (data) {
              this.task_form = { ...this.task_form, 'requireId': data.requirementId, 'name': data.name, 'priority': data.priority }
              this.requirementIdList = { 'name': '需求', 'data': data.requirementId }
            }
            this.task_change_bizId(this.bizId)
            this.taskUpdateRequire(ss.id)
          })
          break
      }
      projectListProject({ bizId: this.bizId }).then(res => { // 获取项目（查询）
        this.projectList = res.data.filter(item => item.id !== -1)
      })
    },
    test2(item, e) { // 获取团队人员信息
      if (typeof this.test[item.idap] === 'undefined') {
        item.role = e
        this.test[item.idap] = item
      }
      return item.idap
    },
    throttleTask: _.throttle(function() {
      this.create_task(...arguments)
    }, 5000, {
      leading: true,
      trailing: false
    }),
    async settingGetBizList() { // 获取业务线列表
      const res = await settingGetMyAndOtherBizList()
      if (res.code === 200) {
        this.bizList = [{
          name: '我的业务线',
          options: res.data[0] || []
        }, {
          name: '其他业务线',
          options: res.data[1] ? res.data[1].filter(item => item.isSecret !== 1) : []
        }]
      }
    },
    async task_change_bizId(biz, id) { // 获取业务线需求
      const data = { bizId: biz }
      id ? data.taskId = id : ''
      const res = await configShowRequirementVersionEnum(data) // 获取需求（查询）
      if (res.code === 200) {
        this.demandList = res.data.filter(item => item.id !== -1)
      }
      this.bugDataGet(biz)
    },
    create_task(e) { // 创建任务（保存）
      this.$refs['task_form'].validate((valid) => {
        if (valid) {
          var taskInfoDO = e
          taskInfoDO.followVersion = e.followVersion
          taskInfoDO.notest = e.notest
          taskInfoDO.source = e.source
          switch (taskInfoDO.source) {
            case 1: // 无归属
              taskInfoDO.requireId = '-1'
              taskInfoDO.projectId = '-1'
              break
            case 2: // 需求
              taskInfoDO.requireId = e.requireId
              taskInfoDO.projectId = ''
              break
            case 3: // 项目
              taskInfoDO.requireId = '-1'
              taskInfoDO.projectId = e.projectId
              break
          }
          if (e.cliType) {
            e.cliType !== '' ? taskInfoDO.bizId = e.cliType[0] : taskInfoDO.bizId = null
            e.cliType !== '' ? taskInfoDO.type = e.cliType[1] : taskInfoDO.type = null
            e.cliType !== '' ? taskInfoDO.clientType = e.cliType[2] : taskInfoDO.clientType = null
          }
          var user = { name: this.userNames, ename: this.userInformation, id: '' }
          taskCreate({ taskInfoDO, user }).then(res => {
            this.dialogFormVisible = false
            this.$message({ message: res.msg, type: 'success', duration: 1000, offset: 150 })
            if (!this.noJump) {
              const bizId_id = EncryptId(`${this.bizId}_${res.data.id}`)
              this.$router.push({ name: '任务详情', query: { bizId_id: bizId_id }})
            } else {
              this.$emit('change')
            }
          })
        }
      })
    },
    uptate_task(e) { // 编辑任务（编辑）
      this.$refs['task_form'].validate((valid) => {
        if (valid) {
          var taskInfoDO = e
          taskInfoDO.followVersion = e.followVersion
          taskInfoDO.source = e.source
          taskInfoDO.notest = e.notest
          taskInfoDO.bizId = e.cliType[0]
          taskInfoDO.type = e.cliType[1]
          taskInfoDO.clientType = e.cliType[2]
          var user = { name: this.userNames, ename: this.userInformation, id: '' }
          taskUpdate({ taskInfoDO, user }).then(res => {
            if (res.code === 200) {
              this.dialogFormVisible = false
              this.$emit('updateIteration')
              this.$message({ message: res.msg, type: 'success', duration: 1000, offset: 150 })
              location.reload()
            }
          })
        }
      })
    },
    remoteMethod(query) { // 人员查询
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          memberQueryMemberInfoByIDAPorName({ memberIDAP: query }).then(res => {
            const obj = {}
            this.options = res.data.reduce((cur, next) => {
              obj[next.idap] ? '' : obj[next.idap] = true && cur.push(next)
              return cur
            }, [])
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    remoteMethod1(query) { // 人员查询
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          memberQueryMemberInfoByIDAPorName({ memberIDAP: query }).then(res => {
            const obj = {}
            this.options1 = res.data.reduce((cur, next) => {
              obj[next.idap] ? '' : obj[next.idap] = true && cur.push(next)
              return cur
            }, [])
          })
        }, 200)
      } else {
        this.options1 = []
      }
    },
    get_source(e) {
      switch (e) {
        case 1:
          this.ascription_demand = false
          this.ascription_project = false
          this.$set(this.task_form, 'bizId', this.bizId)
          this.$set(this.task_form, 'requireId', '')
          this.$set(this.task_form, 'projectId', '')
          this.$set(this.task_form, 'taskIdFromDpm', '')
          this.bugDataGet(this.bizId)
          break
        case 2:
          this.show_schedule = false
          this.ascription_demand = true
          this.ascription_project = false
          this.requirementIdList.name === '需求' ? this.$set(this.task_form, 'requireId', this.requirementIdList.data) : this.$set(this.task_form, 'requireId', '')
          this.$set(this.task_form, 'projectId', '')
          this.tit_Name === '编辑任务' ? this.taskUpdateRequire(this.requirementIdList.data, this.requirementIdList.taskId) : this.getRequireItem({ id: this.requirementIdList.data })
          break
        case 3:
          this.ascription_demand = false
          this.ascription_project = true
          this.$set(this.task_form, 'bizId', this.bizId)
          this.requirementIdList.name === '项目' ? this.$set(this.task_form, 'projectId', this.requirementIdList.data) : this.$set(this.task_form, 'projectId', '')
          this.$set(this.task_form, 'requireId', '')
          this.$set(this.task_form, 'taskIdFromDpm', '')
          this.bugDataGet(this.bizId)
          break
      }
    },
    get_taskSelect() { // 下拉菜单数据
      configShowTaskEnum().then(res => {
        this.noTest = res.data.noTest // 是否免测
        this.taskSource = res.data.taskSource // 归属需求
        this.appClient = res.data.appClient // 涉及客户端
      })
      settingGetBizList({}).then(res => {
        this.all_bizId = res.data
      })
    },
    get_followVersion(e) { // 涉及的客户端（显示/隐藏）
      this.$set(this.task_form, 'involveApp', '')
      e === 1 ? this.show_Client = true : ''
      e === 2 ? this.show_Client = false : ''
    },
    async taskUpdateRequire(requireId, id) {
      const res = await getRelDpmTask({ requireId: requireId, taskId: id })
      if (res.code === 200) {
        const show = res.data.relDpm
        show ? this.show_schedule = show : this.show_schedule = show
        this.arr_schedule = res.data.tasks
      }
    },
    async getRequireItem(val) {
      if (val.id) {
        const res = await getRelDpmTask({ requireId: val.id })
        if (res.code === 200) {
          this.show_schedule = res.data.relDpm
          this.arr_schedule = res.data.tasks
        }
      }
    },
    bugDataGet(bizId) { // 所属模块
      settingQueryBizModuleList(bizId).then(res => {
        this.business_platform_Modular = res.data.map(item => ({
          ...item,
          value: item.id,
          label: item.moduleName,
          children: item.childModules.length === 0 ? null : item.childModules.map(item1 => ({
            ...item1,
            value: item1.id,
            label: item1.moduleName,
            children: item1.childModules.length === 0 ? null : item1.childModules.map(item2 => ({
              ...item2,
              value: item2.id,
              label: item2.moduleName
            }))
          }))
        }))
      })
    }
  }
}
</script>

<style lang="scss">
.copy-task {
  .el-select {
    width: 20vw;
  }
  .el-dialog__body {
    padding: 20px 40px;
  }
  label {
    font-weight: 400;
  }
  .form-item-normal-lable {
    .el-form-item__label:before {
      content: "";
      color: #333333;
      margin-right: 12px;
      font-weight: 400;
    }
  }
  /deep/ .el-dialog__title {
    line-height: 24px;
    font-size: 18px;
    color: #303133;
    padding-left: 10px;
  }
  .blueStripe {
    width:4px;
    height:17px;
    background:#409EFF;
    border-radius:1px;
    position: absolute;
    top: 23px;
    left: 20px;
  }
}
</style>
