<script>
import { get, post, put, postWithHeader, putWithHeader } from '../../../utils/request'
import { userStore } from '@/store/userInfo'
import { productListNameMapping } from '../../../utils/mapping'

export default {
  data () {
    return {
      formData: {
        type: '',
        teamName: '',
        teamDescription: '',
        teamAdminId: [],
        productList: [{
          productId: '',
          licenseNumber: ''
        }]
      },
      flag: '',
      role: '1',
      adminOptions: [],
      projectOptions: [],
      click: true,
      isDefaultTeam: false
    }
  },
  computed: {
    disabled () {
      let isEmpty = true
      isEmpty = this.formData.teamName.trim() === '' && this.formData.teamDescription.trim() === '' && this.formData.teamAdminId.length === 0
      this.formData.productList.forEach((item)=>{
        Object.keys(item).forEach((key)=>{
          if (item[key] !== '' && item[key] !== null && item[key] !== undefined) {
            isEmpty = false
          }
        })
      })
      return isEmpty
    }
  },
  created () {
    this.getAdmin()
    this.getProduct()
    let rowData = {}
    this.role = userStore().user.role
    if (!Object.keys(this.$route.query).length) {
      rowData = JSON.parse(localStorage.getItem('rowData'))
    } else {
      rowData = this.$route.query
      localStorage.setItem('rowData', JSON.stringify(this.$route.query))
    }
    this.flag = rowData.flag
  },
  methods: {
    // 提交表单
    submitForm () {
      // 默认团队不允许修改
      // if(this.isDefaultTeam){
      //   this.$message.error({duration: 5000, message: 'The default team does not allow changes'})
      //   return
      // }
      if(this.click){
        this.click = false
        let emptyFlag = true
        let productArr = []
        for (const item of this.formData.productList) {
          productArr.push(item['productId'])
        }
        emptyFlag = productArr.includes('')
        if (this.formData.teamName.trim() === '' || (this.flag === 'create' ? emptyFlag : false)) {
          this.$message.error({duration: 5000, message: 'Required Information Missing'})
          //限制点击
          setTimeout(() => {
            this.click = true
          }, 3000)
        } else {
          if (this.flag === 'create') this.createTeam()
          if (this.flag === 'edit') this.editTeam()
        }
      }
    },
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    removeDomain(item) {
      if(this.isDefaultTeam || this.role.indexOf('1') === -1){
        return
      }
      var index = this.formData.productList.indexOf(item)
      if (index !== -1) {
        this.formData.productList.splice(index, 1)
      }
      this.changeSelect()
    },
    // 添加卡片
    addDomain () {
      if(this.isDefaultTeam || this.role.indexOf('1') === -1){
        return
      }
      this.changeSelect()
      this.formData.productList.push({
        licenseNumber: '',
        productId: ''
      })
    },
    // 创建团队
    createTeam () {
      let data = JSON.parse(JSON.stringify(this.formData))
      data.productList.forEach(item =>{
        if (item.licenseNumber === null || item.licenseNumber === '') {
          item.licenseNumber = 0
        }
      })
      data.teamAdminId = data.teamAdminId.filter((item) => {
        return item !== 'All'
      })
      postWithHeader('/pdf-tech/vppTeam/createTeam', JSON.stringify(data)).then((res) => {
        //限制点击
        setTimeout(() => {
          this.click = true
        }, 2000)
        if (res.data.code === 200) {
          this.$message({
            duration: 5000,
            message: 'Change Success',
            type: 'success'
          })
          this.$router.push({name:'ManageTeam'})
        } else if (res.data.code === 'Please allocate more license to the team') {
          this.$message.error({duration: 5000, message:'Please assign more license to the team'})
        } else (
          this.$message.error({duration: 5000, message:res.data.msg})
        )
      })
    },
    // 编辑团队
    editTeam () {
      let data = JSON.parse(JSON.stringify(this.formData))
      data.productList.forEach(item =>{
        if (item.licenseNumber === null || item.licenseNumber === '') {
          item.licenseNumber = 0
        }
      })
      data.teamAdminId = data.teamAdminId.filter((item) => {
        return item !== 'All'
      })
      putWithHeader('/pdf-tech/vppTeam/editTeam', JSON.stringify(data)).then((res) => {
        //限制点击
        setTimeout(() => {
          this.click = true
        }, 2000)
        if (res.data.code === 200) {
          this.$message({
            duration: 5000,
            message: 'Modify Successfully',
            type: 'success'
          })
          this.$router.push({name:'ManageTeam'})
        } else if (res.data.msg === 'Insufficient quantity to allocate') {
          this.$message.error({duration: 5000, message:'Insufficient License'})
        } else if (res.data.msg === 'Activated License Code Exceeded') {
          this.$message.error({duration: 5000, message:'Amount of Team License cannot be less than Assigned License'})
        } else (
          this.$message.error(res.data.msg)
        )
      })
    },
    // 获取所有管理员
    getAdmin () {
      get('/pdf-tech/vppRTeamMemberRole/getComponyMenber').then((res) => {
        if (res.data.code === 200) {
          res.data.result.forEach(item => {
            if (item.memberRole !== '1') {
              this.adminOptions.push({
                  label: item.email,
                  value: item.id
              })
            }
          })
          if (this.flag === 'edit') {
            if (this.$route.query.teamId) {
              this.formData.teamId = this.$route.query.teamId
              this.getTeamInfo(this.formData.teamId)
            }
          }
        }
      })
    },
    // 获取所有产品
    getProduct () {
      get('/pdf-tech/product/listWithAdmin').then((res) => {
        if (res.data.code === 200) {
          const list = productListNameMapping(res.data.result)
          list.forEach(item => {
            this.projectOptions.push({
                label: item.name,
                value: item.id,
                disabled: false
            })
          })
        }
      })
    },
    // Team Admin下拉框全选功能
    selectAllAdmin () {
      if (this.formData.teamAdminId.length < this.adminOptions.length) {
        this.formData.teamAdminId = []
        this.adminOptions.map((item) => {
          this.formData.teamAdminId.push(item.value)
        })
        this.formData.teamAdminId.unshift('All')
      } else {
        this.formData.teamAdminId = []
      }
    },
    changeSelectAdmin (val) {
      if (!val.includes('All') && val.length === this.adminOptions.length) {
        this.formData.teamAdminId.unshift('All')
      } else if (val.includes('All') && (val.length - 1) < this.adminOptions.length) {
        this.formData.teamAdminId = this.formData.teamAdminId.filter((item) => {
          return item !== 'All'
        })
      }
    },
    removeTag (val) {
      if (val === 'All') {
        this.formData.teamAdminId = []
      }
    },
    // 编辑团队时获取团队信息
    getTeamInfo (id) {
      get('/pdf-tech/vppTeam/getTeamProductInfo?teamId=' + id).then((res) => {
        if (res.data.code === 200) {
          this.type = res.data.result.type
          if(res.data.result.type === 1){
            this.isDefaultTeam = true
          }
          this.formData.teamName = res.data.result.teamName
          this.formData.teamDescription = res.data.result.teamDescription
          if (res.data.result.productList.length > 0) {
            this.formData.productList = productListNameMapping(res.data.result.productList)
          }
          const teamAdminId = []
          res.data.result.teamAdminList.forEach(item => {
            teamAdminId.push(item.adminId)
          })
          for (let i = 0; i < teamAdminId.length; i++) {
            this.adminOptions.map(item => {
              if(item['value'] === teamAdminId[i]) {
                this.formData.teamAdminId.push(item.value)
              }
            })
          }
          if (this.adminOptions.length === this.formData.teamAdminId.length && this.formData.teamAdminId.length !== 0) {
            this.formData.teamAdminId.unshift('All')
          }
          this.changeSelect()
        }
      })
    },
    // 已经选择过的产品不能选
    changeSelect () {
      let idList = []
      this.formData.productList.forEach((item) => {
        idList.push(item.productId)
      })
      this.projectOptions.forEach((items) => {
        items.disabled = idList.includes(items.value)
      })
    }
  },
  // 切换路由时清除本地存储数据
  beforeRouteLeave (to, from, next) {
    localStorage.removeItem('rowData')
    next()
  }
}
</script>

<template>
  <div>
    <h1>{{ flag === 'create' ? 'Create' : 'Edit'}} Team</h1>
    <div class="block mt-24px p-40px pr-50px">
      <el-form label-position="top" label-width="80px" :model="formData" ref="formData">
        <el-form-item>
          <template slot="label">
            <span>Team Name</span>
            <span class="text-[#FF5054]">*</span>
          </template>
          <el-input v-model="formData.teamName" class="under-border" placeholder="Team Name"></el-input>
        </el-form-item>
        <el-form-item label="Team Description">
          <el-input v-model="formData.teamDescription" class="under-border" placeholder="Describe you team"></el-input>
        </el-form-item>
        <el-form-item label="Team Admin">
          <el-select
            :disabled="role.indexOf('1') === -1 || type === 3"
            v-model="formData.teamAdminId"
            @change='changeSelectAdmin'
            @remove-tag='removeTag'
            multiple
            placeholder="Name of team admin"
            class="w-600px">
            <el-option v-if="adminOptions.length" value="All" @click.native='selectAllAdmin'>All</el-option>
            <el-option
              v-for="item in adminOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <div class="w-600px border-1 border-[#1460F3] rounded-8px p-12px pb-0 mb-24px relative" v-for="(item, index) in formData.productList" :key="index">
          <img v-show="formData.productList.length > 1 && role.indexOf('1') !== -1  && !isDefaultTeam" src="@/assets/images/minus.png" alt="minus" class="w-24px h-24px absolute top-[-12px] right-[-12px] cursor-pointer" @click.prevent="removeDomain(item)">
          <el-form-item>
            <template slot="label">
              <span>Product</span>
              <span class="text-[#FF5054]">*</span>
            </template>
            <select v-model="item.productId" 
              placeholder="Project" 
              class="w-[100%] !h-40px !pl-12px focus-visible:(outline-none)" 
              :class="{ '!text-[#232A40]': item.productId !== '' }"
              :disabled="isDefaultTeam || role.indexOf('1') === -1"
              @change="changeSelect()">
              <option value="" :disabled="isDefaultTeam || role.indexOf('1') === -1">Select Assigned Product</option>
              <option v-for="item in projectOptions" :key="item.value" :value="item.value" :disabled="isDefaultTeam || role.indexOf('1') === -1 || item.disabled">{{ item.label }}</option>
            </select>
          </el-form-item>
          <el-form-item label="Amount of Team License" class="!mb-22px">
            <el-input :disabled="role.indexOf('1') === -1 || isDefaultTeam" v-model.number="item.licenseNumber" placeholder="Enter number of team license"></el-input>
          </el-form-item>
        </div>
        <div class="w-600px h-48px border-1 border-dashed border-[#1460F3] rounded-8px flex justify-center items-center" v-if="role.indexOf('1') !== -1 && !isDefaultTeam">
          <img src="@/assets/images/add.png" alt="add" class="w-24px h-24px cursor-pointer" @click="addDomain">
        </div>
        <div class="mt-32px flex">
          <router-link :to="{ name: 'ManageTeam' }">
            <div class="w-152px h-40px border-1 border-[#1460F3] rounded-8px text-center text-16px text-[#1460F3] font-700 leading-40px mr-16px hover:border-[#1460F3cc] hover:text-[#3776f2]"
              @click="resetForm('formData')">Cancel</div>
          </router-link>
          <div :class="disabled ? 'cursor-not-allowed' : 'cursor-pointer'">
            <div class="w-152px h-40px border-1 border-[#1460F3] rounded-8px bg-[#1460F3] text-center text-16px text-[#fff] font-700 leading-40px"
              :class="disabled ? 'opacity-20 pointer-events-none' : 'hover:bg-[#3776f2]'"
              @click="submitForm()">Save</div>
          </div>
        </div> 
      </el-form>
    </div>
    <!-- <el-dialog
      title=""
      :visible.sync="dialogVisible"
      width="376px"
      center
      :show-close="false"
    >
      <img src="@/assets/images/close_user.png" alt="close_user" class="inline-block w-48px h-48px">
      <div class="mt-16px text-16px leading-24px text-[#232A40]">
        <p>Your TEAM ADMIN is not on the team.<br />Invite <span class="font-bold">{{ formData.teamAdminId[0] }}</span> to Team Kdan？</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">Change Admin</el-button>
        <el-button type="primary" @click="dialogVisible = false">Invite</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>

<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 24px;
}
::v-deep .under-border .el-input__inner {
  border-top: none;
  border-left: none;
  border-right: none;
  border-radius: 0;
}
::v-deep.el-form--label-top .el-form-item__label {
  padding: 0 0 4px 12px;
  font-size: 14px;
  line-height: 20px;
  color: #232A40;
  font-weight: 700;
}
::v-deep .el-select {
  .el-input__inner {
    border-color: #D9D9D9;
  }
  .el-input .el-select__caret {
    color: #808185;
    font-weight: bold;
  }
  .el-tag {
    border-color: #8D9CB9;
    background-color: #EEF4FF;
    margin-left: 8px;
  }
  .el-tag.el-tag--info {
    color: #505258;
    font-size: 14px;
    padding-left: 4px;
  }
  .el-tag__close.el-icon-close {
    background-color: transparent;
    color: #8D9CB9;
    font-size: 20px;
    font-weight: bold;
  }
}
</style>