<template>
  <normal-dialog
    :show-dialog.sync="show"
    :title="title"
    :is-default-close="false"
    width="60%"
    :show-footer="!disabled"
    @confirm="confirmForm()"
    @cancel="cancel()"
  >
    <article>
      <h2 v-show="type==='require'" class="form-title">需求范围</h2>
      <h2 v-show="type==='task'" class="form-title">任务范围</h2>
      <el-form ref="form" :model="formData" label-width="100px" label-position="left">
        <el-form-item v-if="type === 'require'" label="需求方向">
          <el-cascader
            v-model="formData.requireOrientIdList"
            size="small"
            collapse-tags
            :props="requireProps"
            :options="directionList"
            placeholder="请选择"
            clearable
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item v-if="type === 'task'" label="技术模块">
          <el-cascader
            v-model="formData.techModuleIdList"
            size="small"
            collapse-tags
            :props="requireProps"
            :options="directionList"
            placeholder="请选择"
            clearable
            :disabled="disabled"
          />
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="formData" label-width="100px" label-position="left" :inline="true">
        <el-form-item label="跟版客户端">
          <el-select v-model="formData.clientId" placeholder="请选择" size="small" :disabled="disabled">
            <el-option v-for="item in appClientList" :key="'app'+item.code" :label="item.msg" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formData.clientVersionId" placeholder="请选择" size="small" :disabled="disabled">
            <el-option v-for="item in clientList" :key="'client'+item.code" :label="item.msg" :value="item.code" />
          </el-select>
        </el-form-item>
      </el-form>
      <h2 class="form-title">通知条件（必选）</h2>
      <el-form ref="form" :model="formData" label-width="100px" label-position="left">
        <el-form-item v-for="(item,index) in formData.noticeConditionList" :key="'condition'+index" label="条件">
          <el-select v-model="item.type" placeholder="请选择类型" size="small" class="condition-select" :disabled="disabled" @change="changeNoticeItem(item)">
            <el-option v-for="key in typeList" :key="key.label" :label="key.label" :value="key.value" />
          </el-select>
          <el-select v-show="item.type === 1 || item.type === 3" v-model="item.status" placeholder="请选择状态" size="small" class="condition-select" :disabled="disabled">
            <el-option v-for="key in statusList" :key="'status'+key.code" :label="key.msg" :value="key.code" />
          </el-select>
          <el-select v-show="item.type === 1 || item.type === 3" v-model="item.triggerEvent" placeholder="请选择" size="small" class="condition-select" :disabled="disabled">
            <el-option v-for="key in triggerList" :key="'trigger'+key.code" :label="key.name" :value="key.code" />
          </el-select>
          <el-select v-show="item.type === 2 || item.type === 4" v-model="item.triggerEvent" placeholder="请选择" size="small" class="condition-select" :disabled="disabled">
            <el-option v-for="key in noticeEventList" :key="'event'+key.code" :label="key.name" :value="key.code" />
          </el-select>
          <el-select v-show="item.type === 1 || item.type === 3" v-model="item.greaterTime" placeholder="请选择" size="small" class="condition-select" :disabled="disabled">
            <el-option v-for="key in rangDaysList" :key="'greaterTime'+key.value" :label="key.label" :value="key.value" />
          </el-select>
          <el-select v-show="item.type === 2 || item.type === 4" v-model="item.lessTime" placeholder="请选择" size="small" class="condition-select" :disabled="disabled">
            <el-option v-for="key in aheadDaysList" :key="'lessTime'+key.value" :label="key.label" :value="key.value" />
          </el-select>
          <i v-show="!disabled" class="el-icon-remove-outline" @click="removeItem(index)" />
        </el-form-item>
        <div v-show="!disabled" class="add-condition" @click="addCondition()"><i class="el-icon-circle-plus-outline" /> 添加条件</div>
      </el-form>
      <h2 class="form-title">通知方式（必选）</h2>
      <el-form ref="form" :model="formData" label-width="100px" label-position="left">
        <!-- 邮件方式 -->
        <el-checkbox v-model="noticeList.Email" class="notice-check" :disabled="disabled">邮件</el-checkbox>
        <el-form-item v-for="(item,index) in EmailList" :key="'email'+index" :label="index===0?'通知人群':''">
          <el-select v-model="item.type" placeholder="请选择" size="small" class="condition-select" :disabled="disabled" @change="changeNoticeType(item)">
            <el-option v-for="key in noticeGroupList" :key="'email-type'+key.label" :label="key.label" :value="key.value" />
          </el-select>
          <el-select v-show="item.type===1" v-model="item.teams" placeholder="请选择" size="small" :multiple="true" :disabled="disabled">
            <el-option v-for="key in teamList" :key="'email-team'+key.teamId" :label="key.teamName" :value="key.teamId" />
          </el-select>
          <search-people v-show="item.type===2" :value.sync="item.customStaffs" :clearable="false" :multiple="true" :disabled="disabled" />
          <i v-if="index!==0 && !disabled" class="el-icon-remove-outline" @click="removeMembers(EmailList,index)" />
        </el-form-item>
        <div v-show="noticeList.Email && !disabled" class="add-notice" @click="addMembers(EmailList)"><i class="el-icon-circle-plus-outline" /> 添加人群</div>
        <!-- DChart系统方式 -->
        <el-checkbox v-model="noticeList.DChart" class="notice-check" :disabled="disabled">DChart系统通知</el-checkbox>
        <el-form-item v-for="(item,index) in DChartList" :key="'DChart'+index" :label="index===0?'通知人群':''">
          <el-select v-model="item.type" placeholder="请选择" size="small" class="condition-select" :disabled="disabled" @change="changeNoticeType(item)">
            <el-option v-for="key in noticeGroupList" :key="'DChart-type'+key.label" :label="key.label" :value="key.value" />
          </el-select>
          <el-select v-show="item.type===1" v-model="item.teams" placeholder="请选择" size="small" :multiple="true" :disabled="disabled">
            <el-option v-for="key in teamList" :key="'DChart-team'+key.teamId" :label="key.teamName" :value="key.teamId" />
          </el-select>
          <search-people v-show="item.type===2" :value.sync="item.customStaffs" :clearable="false" :multiple="true" :disabled="disabled" />
          <i v-if="index!==0 && !disabled" class="el-icon-remove-outline" @click="removeMembers(DChartList,index)" />
        </el-form-item>
        <div v-show="noticeList.DChart && !disabled" class="add-notice" @click="addMembers(DChartList)"><i class="el-icon-circle-plus-outline" /> 添加人群</div>
        <!-- DChart群方式 -->
        <el-checkbox v-model="noticeList.Group" class="notice-check" :disabled="disabled">DChart群通知</el-checkbox>
        <div v-show="noticeList.Group && !disabled" class="add-condition">
          <ul v-show="GroupList.length>0" class="group-list">
            <li v-for="(item,index) in GroupList" :key="'gourp-item'+ index" class="group-item">
              <div>{{ item.name }}</div>
              <div>{{ item.url }}</div>
              <span><i class="el-icon-delete" @click.stop="removeGroup(index)" /></span>
            </li>
          </ul>
          <span @click="showGroupForm = true"><i class="el-icon-circle-plus-outline" /> 添加DChart群</span>
          <section v-if="showGroupForm" class="group-form">
            <el-form ref="groupForm" :model="GroupItem" :rules="groupRules" label-width="200px" label-position="left">
              <el-form-item prop="name" label="群名称或群ID">
                <el-input
                  v-model="GroupItem.name"
                  type="textarea"
                  maxlength="150"
                  show-word-limit
                  :autosize="{ minRows: 1, maxRows: 5 }"
                />
              </el-form-item>
              <el-form-item prop="url" label="机器人webhook地址">
                <el-input
                  v-model="GroupItem.url"
                  type="textarea"
                  maxlength="200"
                  show-word-limit
                  :autosize="{ minRows: 3, maxRows: 6 }"
                />
              </el-form-item>
            </el-form>
            <div class="group-confirm">
              <el-button size="small" @click.stop="showGroupForm = false">取消</el-button>
              <el-button type="primary" size="small" @click.stop="addGroup()">确认</el-button>
            </div>
          </section>
        </div>
      </el-form>
      <h2 class="form-title">通知时刻</h2>
      <div class="notice-time">
        <el-time-select
          v-model="formData.noticeTime"
          placeholder="任意时间点"
          size="small"
          value-format="HH:mm"
          :picker-options="{
            start: '00:00',
            step: '00:15',
            end: '23:45',
          }"
          :disabled="disabled"
        />
      </div>
    </article>
  </normal-dialog>
</template>
<script>
const _ = require('lodash')
import {
  showRequireStatusEnum,
  showTaskStatusEnum,
  getBizNoticeSettingEnum,
  addBizNoticeSetting,
  updateBizNoticeSetting
} from '@/api/configure'
import { settingQueryBizRqmtOrntList } from '@/api/requirement.js'
import { settingQueryBizModuleList } from '@/api/defectManage'
import { queryTeamInfoList } from '@/api/workSchedule'
import { showAppClientEnum } from '@/api/version.js'
import normalDialog from '@/components/dialog/normalDialog'
import searchPeople from '@/components/select/searchPeople'
export default {
  components: { normalDialog, searchPeople },
  props: {
    data: {
      type: Object,
      default: () => null,
      required: false
    },
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    type: {
      type: String,
      default: 'require', // 需求:require,任务:task
      required: false
    },
    disabled: {// 查看状态，不可修改
      type: Boolean,
      default: false,
      required: false
    },
    copy: {// 复制
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      bizId: Number(localStorage.getItem('bizId')),
      title: this.type === 'require' ? '新建需求定时通知' : '新建任务定时通知',
      requireProps: {
        value: 'id',
        label: 'rqmtOrntName',
        children: 'childRqmtOrnts',
        multiple: true
      },
      directionList: [], // 需求方面列表
      modulesList: [], // 任务模块列表
      formData: {
        bizId: Number(localStorage.getItem('bizId')),
        requireOrientIdList: [], // 需求方向
        techModuleIdList: [], // 技术模块
        clientId: null, // 客户端
        clientVersionId: null, // 版本
        noticeConditionList: [], // 条件列表
        noticeSetting: {}, // 通知方式
        noticeTime: null // 通知时刻
      },
      EmailList: [], // Email通知列表
      DChartList: [], // DChart系统通知列表
      GroupList: [], // DChart群通知列表
      GroupItem: { name: null, url: null }, // 当前群添加对象
      showGroupForm: false,
      groupRules: {// 群填写规则
        name: [{ required: true, message: '请填写群名称或群ID', trigger: 'change' }],
        url: [{ required: true, message: '请填写机器人webhook地址', trigger: 'change' }]
      },
      noticeList: {// 通知方式列表
        Email: false, // 邮件通知
        DChart: false, // DChart系统通知
        Group: false // DChart群通知
      },
      noticeGroupList: [], // 通知人群类型选择列表
      teamList: [], // 团队选择列表
      show: this.visible, // 显示弹框
      appClientList: [], // 客户端选择列表
      typeList: [], // 条件类型选择列表
      statusList: [], // 状态选择列表
      noticeEventList: [], // 事件列表
      triggerList: [], // 触发事件： 0 停留 1 交付 2 提测
      aheadDaysList: [
        { label: '3天前开始提醒', value: 3 },
        { label: '2天前开始提醒', value: 2 },
        { label: '1天前开始提醒', value: 1 },
        { label: '过期提醒', value: 0 }
      ], // 提前几天提醒
      rangDaysList: [] // 条件中大于天数列表
    }
  },
  computed: {
    clientList: { // 版本列表
      get() {
        if (this.formData.clientId !== null) {
          const obj = this.appClientList.find(item => item.code === this.formData.clientId)
          return (obj && obj.childEnumInfos) || []
        } else {
          return []
        }
      }
    }
  },
  watch: {
    data: {
      handler(newV) {
        if (newV) {
          this.initData(_.cloneDeep(newV))
        }
      },
      deep: true,
      immediate: true
    },
    type: {
      handler(newV) {
        this.type = newV
      },
      immediate: true
    },
    visible: {
      handler(newV) {
        this.show = newV
      },
      immediate: true
    },
    copy: {
      handler(newV) {
        this.copy = newV
      },
      immediate: true
    },
    disabled: {
      handler(newV) {
        this.disabled = newV
      },
      immediate: true
    },
    // 'formData.clientId': { // 客户端改变，版本默认取第一个版本
    //   handler(newV) {
    //     this.formData.clientVersionId = (this.clientList[0] && this.clientList[0].code) || null
    //   }
    // },
    'noticeList.Email': {
      handler(newV, oldV) {
        if (newV) {
          if (this.EmailList.length === 0) this.EmailList.push({ type: 0, member: false, teams: [], customStaffs: [] })
        } else {
          this.EmailList = []
        }
      }
    },
    'noticeList.DChart': {
      handler(newV, oldV) {
        if (newV) {
          if (this.DChartList.length === 0) this.DChartList.push({ type: 0, member: false, teams: [], customStaffs: [] })
        } else {
          this.DChartList = []
        }
      }
    }
  },
  created() {
    this.getBizNoticeSettingEnum()
    this.getRequireDirection()
    this.settingQueryBizModuleList()
    this.showAppClientEnum()
    this.queryTeamInfoList()
    this.init()
  },
  methods: {
    initData(data) {
      this.formData = {
        id: data.id,
        bizId: data.bizId,
        requireOrientIdList: data.requireOrientIdList, // 需求方向
        techModuleIdList: data.techModuleIdList, // 技术模块
        clientId: data.clientId || null, // 客户端
        clientVersionId: data.clientVersionId, // 版本
        noticeConditionList: data.noticeConditionList || [], // 条件列表
        noticeSetting: {}, // 通知方式
        noticeTime: data.noticeTime // 通知时刻
      }
      if (data.noticeSetting.email && data.noticeSetting.email.length > 0) {
        this.EmailList = Array(data.noticeSetting.email.length).fill({ type: 0, member: false, teams: [], customStaffs: [] })
        this.$nextTick(() => {
          this.EmailList = data.noticeSetting.email
        })
        this.noticeList.Email = true
      }
      if (data.noticeSetting.dChat && data.noticeSetting.dChat.length > 0) {
        this.DChartList = Array(data.noticeSetting.dChat.length).fill({ type: 0, member: false, teams: [], customStaffs: [] })
        this.$nextTick(() => {
          this.DChartList = data.noticeSetting.dChat
        })
        this.noticeList.DChart = true
      }
      if (data.noticeSetting.dChatGroup && data.noticeSetting.dChatGroup.length > 0) {
        this.GroupList = data.noticeSetting.dChatGroup || []
        this.noticeList.Group = true
      }
    },
    async getBizNoticeSettingEnum() { // 任务需求事件列表
      const res = await getBizNoticeSettingEnum(this.bizId)
      if (res.code === 200) {
        this.triggerList = res.data.noticeConditionOpList
        this.type === 'require'
          ? this.noticeEventList = res.data.noticeEventRequireOpList
          : this.noticeEventList = res.data.noticeEventTaskOpList
      }
    },
    async getRequireDirection() { // 需求方向列表
      const res = await settingQueryBizRqmtOrntList(this.bizId)
      if (res.code === 200) {
        this.directionList = this.getRequireData(res.data)
      }
    },
    async settingQueryBizModuleList() { // 任务模块列表
      const res = await settingQueryBizModuleList(this.bizId)
      if (res.code === 200) {
        this.modulesList = this.getTaskData(res.data)
      }
    },
    getRequireData(data) {
      for (var i = 0; i < data.length; i++) {
        data[i].childRqmtOrnts.length < 1 ? delete data[i].childRqmtOrnts : this.getRequireData(data[i].childRqmtOrnts)
      }
      return data
    },
    getTaskData(data) {
      for (var i = 0; i < data.length; i++) {
        data[i].childModules.length < 1 ? delete data[i].childModules : this.getTaskData(data[i].childModules)
      }
      return data
    },
    async showAppClientEnum() { // 获取客户端列表
      const res = await showAppClientEnum()
      if (res.code === 200) {
        this.appClientList = res.data.appClient
      }
    },
    async showRequireStatusEnum() { // 获取需求状态列表
      const res = await showRequireStatusEnum(this.bizId)
      if (res.code === 200) {
        this.statusList = res.data.requirementStatus || []
      }
    },
    async showTaskStatusEnum() { // 获取任务状态列表
      const res = await showTaskStatusEnum(this.bizId)
      if (res.code === 200) {
        this.statusList = res.data.taskStatus || []
      }
    },
    async queryTeamInfoList() { // 获取用户团队列表
      const res = await queryTeamInfoList({ curIndex: 1, pageSize: 9999 })
      if (res.code === 200 && res.data) {
        this.teamList = res.data.list
      }
    },
    init() {
      if (this.type === 'require') {
        this.typeList = [{ label: '需求状态', value: 1 }, { label: '需求事件', value: 2 }]
        this.noticeGroupList = [{ label: '需求成员', value: 0 }, { label: '团队', value: 1 }, { label: '自定义人员', value: 2 }]
        this.showRequireStatusEnum()
      } else {
        this.typeList = [{ label: '任务状态', value: 3 }, { label: '任务事件', value: 4 }]
        this.noticeGroupList = [{ label: '任务成员', value: 0 }, { label: '团队', value: 1 }, { label: '自定义人员', value: 2 }]
        this.showTaskStatusEnum()
      }
      let i = 1
      while (i <= 100) {
        this.rangDaysList.push({ label: `大于${i}天`, value: i })
        i++
      }
    },
    changeNoticeItem(item) { // 修改条件
      if (item.type === 0) {
        item.triggerEvent = this.triggerList[0].code
      } else if (item.type === 1) {
        item.triggerEvent = this.noticeEventList[0].code
      }
    },
    addCondition() { // 添加条件
      this.formData.noticeConditionList.push({
        type: this.typeList[0].value, // 1 需求状态 2 需求事件 3 任务状态 4 任务事件
        status: 0,
        triggerEvent: 0, // 触发事件： 0 停留 1 交付 2 提测
        greaterTime: 1, // 大于的时间
        lessTime: 3 // 提前提醒的时间
      })
    },
    removeItem(index) { // 移除条件
      this.formData.noticeConditionList.splice(index, 1)
    },
    addMembers(list) { // 添加成员
      list.push({ type: 0, member: false, teams: [], customStaffs: [] })
    },
    removeMembers(list, index) { // 移除成员
      list.splice(index, 1)
    },
    changeNoticeType(item) { // 修改通知
      switch (item.type) {
        case 0:
          item.member = true
          item.teamList = []
          item.customStaffList = []
          break
        case 1:
          item.member = false
          item.customStaffList = []
          break
        case 2:
          item.member = false
          item.teamList = []
          break
      }
    },
    addGroup() { // 添加DChart群
      this.$refs['groupForm'].validate((valid) => {
        if (valid) {
          this.GroupList.push({
            type: 3,
            ...this.GroupItem
          })
          this.GroupItem = { name: null, url: null }
          this.showGroupForm = false
        }
      })
    },
    removeGroup(index) { // 移除DChart群
      this.GroupList.splice(index, 1)
    },
    validate() { // 校验入参
      if (this.formData.techModuleIdList.length < 1 && this.type === 'task') {
        this.$message({ message: '请选择技术方向', type: 'error', duration: 1000, offset: 150 })
        return false
      }
      if (!this.formData.clientId) {
        this.$message({ message: '请选择客户端', type: 'error', duration: 1000, offset: 150 })
        return false
      }
      if (this.formData.noticeConditionList.length < 1) {
        this.$message({ message: '请添加通知条件', type: 'error', duration: 1000, offset: 150 })
        return false
      }
      if (this.EmailList.length === 0 && this.DChartList.length === 0 && this.GroupList.length === 0) {
        this.$message({ message: '请选择一种通知方式', type: 'error', duration: 1000, offset: 150 })
        return false
      }
      if (!this.formData.noticeTime) {
        this.$message({ message: '请选择通知时刻', type: 'error', duration: 1000, offset: 150 })
        return false
      }
      this.formData.noticeSetting = {
        email: this.noticeList.Email ? this.EmailList : [],
        dChat: this.noticeList.DChart ? this.DChartList : [],
        dChatGroup: this.noticeList.Group ? this.GroupList : []
      }
      this.data && !this.copy ? this.updateBizNoticeSetting() : this.addBizNoticeSetting()
    },
    async addBizNoticeSetting() { // 新增通知
      if (this.formData.id) {
        delete this.formData.id
      }
      const res = await addBizNoticeSetting(this.formData)
      if (res.code === 200) {
        this.$message({ message: '添加成功', type: 'success', duration: 1000, offset: 150 })
        this.$emit('confirm')
      }
    },
    async updateBizNoticeSetting() { // 更新通知
      const res = await updateBizNoticeSetting(this.formData)
      if (res.code === 200) {
        this.$message({ message: '修改成功', type: 'success', duration: 1000, offset: 150 })
        this.$emit('confirm')
      }
    },
    confirmForm() {
      this.validate()
    },
    cancel() {
      this.show = false
      this.$emit('update:visible', this.show)
      this.$emit('cancel')
    }
  }
}
</script>
<style lang="scss" scoped>
article::-webkit-scrollbar{
  display: none;
}
article{
  max-height: 500px;
  overflow: scroll;
  padding: 0 45px;
  .form-title {
    margin: 0;
    padding: 0;
    font-size: 18px;
    color: #333333;
    margin: 20px 0;
  }
  .form-title:nth-child(1){
    margin-top: 0;
  }
  /deep/.el-form-item {
    font-size: 14px;
    margin-bottom: 10px;
    label {
      color: #666666;
      font-weight: 400;
    }
  }
  .condition-select {
    width: 22%;
  }
  .add-condition,.add-notice {
    cursor: pointer;
    color: #409EFF;
    position: relative;
  }
  .add-notice {
    margin-left: 100px;
    width: 150px;
  }
  .notice-check{
    margin: 15px 0;
    display: block;
    width: 150px;
  }
  .notice-check:nth-child(1){
    margin-top: 0;
  }
  .el-icon-remove-outline {
    cursor: pointer;
    color: #409EFF;
    font-size: 14px;
    margin-left: 5px;
  }
}
.group-form {
  width: 280px;
  position: absolute;
  bottom: 30px;
  left: 0;
  padding: 10px;
  z-index: 99;
  background:rgba(255,255,255,1);
  box-shadow:0px 0px 12px rgba(0,0,0,0.1);
  /deep/.el-form-item{
    display: flex;
    flex-direction: column;
    margin-bottom: 10px;
    .el-form-item__content {
      margin: 0 !important;
      width: 100%;
      line-height: 10px;
    }
  }
  .group-confirm {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    button:nth-child(1) {
      margin-right: 10px;
    }
  }
}
.group-list{
  margin: 0;
  padding: 0;
  list-style: none;
  width: 100%;
  color: #333333;
  font-size: 14px;
  .group-item {
    margin: 0;
    padding: 0;
    list-style: none;
    width: 100%;
    display: grid;
    grid-template-columns: 30% 60% 10%;
    border:1px solid rgba(209,208,208,1);
    height:37px;
    border-radius: 4px;
    margin-bottom: 10px;
    align-items: center;
    div{
      border-right:1px solid rgba(209,208,208,1);
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      text-align: center;
      line-height: 37px;
      padding: 0 5px;
    }
    span {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
    }
  }
}
</style>
