<template>
  <div class="app-container">
    <el-container>
      <el-header>
        <div>安装包发布任务</div>
        <el-divider/>
      </el-header>
      <el-main>
        <div class="form-main">
          <el-form ref="formAdd" v-loading="$store.state.app.isLoading" :label-width="'120px'" :model="list"
                   :rules="rules"
          >
            <el-form-item label="发布版本">
              <span>{{ list.version }} ({{ list.platformName }})</span>
            </el-form-item>
            <el-form-item label="发布类型" prop="grayFlag">
              <el-radio v-model="list.grayFlag" label="0">灰度</el-radio>
              <el-radio v-model="list.grayFlag" label="1">正式</el-radio>
            </el-form-item>
            <el-form-item label="升级模式" prop="upgradeMode">
              <el-radio v-model="list.upgradeMode" label="0">非强制升级</el-radio>
              <el-radio v-model="list.upgradeMode" label="1">强制升级</el-radio>
            </el-form-item>
            <el-form-item label="升级描述" prop="upgradeDesp">
              <el-input v-model="list.upgradeDesp" class="remark-input" maxlength="50" placeholder="请输入升级描述"
                        show-word-limit
                        type="textarea"
              />
            </el-form-item>
            <template v-if="list.grayFlag =='0'">
              <el-form-item label="发布条件" prop="releaseDestType">
                <el-radio v-model="list.releaseDestType" label="0">白名单</el-radio>
                <el-radio v-model="list.releaseDestType" label="1">时间窗</el-radio>
              </el-form-item>
              <el-form-item v-if="list.releaseDestType =='0'" label="白名单" prop="whiteListId">
                <template>
                  <el-cascader v-model="list.whiteListId" :options="whiteOptions" :show-all-levels="false" clearable/>
                </template>
              </el-form-item>
              <el-form-item v-if="list.releaseDestType =='1'" label="结束日期" prop="expiryTime">
                <template>
                  <div class="block">
                    <el-date-picker
                        v-model="list.expiryTime"
                        placeholder="选择日期时间"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                    />
                  </div>
                </template>
              </el-form-item>
              <el-form-item v-if="list.releaseDestType =='1'" label="灰度人数">
                <el-radio v-model="list.numType" label="0">无限制</el-radio>
                <el-radio v-model="list.numType" label="1">限制</el-radio>
                <el-input-number v-model="list.grayUserNum" :disabled="list.numType == '0'" :max="1000000000"
                                 :min="1" controls-position="right" placeholder="请输入灰度人数"
                />
              </el-form-item>
              <el-form-item label="备注" prop="desp">
                <el-input v-model="list.desp" class="remark-input" maxlength="50" placeholder="请输入备注"
                          show-word-limit
                          type="textarea"
                />
              </el-form-item>
              <el-form-item :prop="list.rule.regularRule? 'releaseRuleId': 'headerOperations'" label="高级规则">
                <template>
                  <el-row>
                    <el-col :span="5">
                      <el-checkbox v-model="list.rule.regularRule">常用规则</el-checkbox>
                    </el-col>
                    <el-col :span="12">
                      <el-select v-model="list.releaseRuleId" :disabled="!list.rule.regularRule" filterable>
                        <el-option
                            v-for="item in releaseOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                      </el-select>
                    </el-col>
                  </el-row>
                  <el-row class="form-row">
                    <el-col :span="5">
                      <el-checkbox v-model="list.rule.customRule">自定义</el-checkbox>
                    </el-col>
                  </el-row>
                  <el-row v-if="list.rule.customRule" class="form-row">
                    <el-table
                        :data="list.headerOperations"
                        border
                        class="custom-table"
                        size="mini"
                    >
                      <el-table-column align="center" label="类型">
                        <template slot-scope="scope">
                          <el-select v-model="scope.row.type" :disabled="disabledCode" placeholder="请选择"
                                     @change="value=>{dictionaryTypeChange(scope.$index,scope.row.type)}"
                          >
                            <el-option
                                v-for="item in typeList"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                            />
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column align="center" label="条件">
                        <template slot-scope="scope">
                          <el-select v-model="scope.row.operType" :disabled="disabledCode" placeholder="请选择">
                            <el-option label="包含" value="1"/>
                            <el-option label="不包含" value="0"/>
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column align="center" label="发布条件">
                        <template slot-scope="scope">
                          <el-select v-model="scope.row.value" :disabled="disabledCode" placeholder="请选择">
                            <el-option v-for="item in scope.row.dictionaryList" :key="item.value" :label="item.value"
                                       :value="item.value"
                            />
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column align="center" border label="操作" width="80">
                        <template slot-scope="scope">
                          <el-button :disabled="disabledCode" round size="mini" type="danger"
                                     @click="deleteHeaderOption(scope.$index)"
                          >
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div v-if="!disabledCode" class="addRow" @click="addHeaderOption()">
                      <i class="el-icon-circle-plus-outline"/>
                      <a class="color-3B77FF">新增一行</a>
                    </div>
                  </el-row>
                </template>
              </el-form-item>
            </template>
            <template v-if="list.grayFlag =='1'">
              <el-form-item label="备注" prop="desp">
                <el-input v-model="list.desp" class="remark-input" maxlength="50" placeholder="请输入备注"
                          show-word-limit
                          type="textarea"
                />
              </el-form-item>
            </template>
            <el-form-item>
              <el-button type="primary" @click="addNew()">新增发布任务</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
  </div>

</template>
<script>
// import { getDictionaryList, getInstallTaskAdd, getReleaseRuleList, getTypeList, getWhiteList } from '@/api/FDS'

export default {
  name: 'InstallationPackTask',
  components: {},
  data() {
    var checkHeader = (rule, value, callback) => {
      if (this.list.rule.customRule) {
        value.forEach(ele => {
          for (const key in ele) {
            if (Object.hasOwnProperty.call(ele, key)) {
              const item = ele[key]
              if (!item && key !== 'desp') {
                return callback(new Error('请输入自定义规则必填项'))
              }
            }
          }
        })
      }
      callback()
    }
    var checkRadix = (rule, value, callback) => {
      if (this.list.rule.regularRule && !value) {
        return callback(new Error('请选择常用规则'))
      }
      callback()
    }
    return {
      selectValue: 'code',
      checkList: ['Android'],
      disabledCode: false,
      list: {
        rule: {
          regularRule: false,
          customRule: false
        },
        // headerOperations: [],
        packId: '', // 安装包ID
        grayFlag: '0', // 发布类型: 0灰度 1正式
        upgradeMode: '0', //
        releaseDestType: '0', // 发布条件： 0白名单 1时间窗
        headerOperations: [// 自定义规则
          // {
          //   'scope': '', // 范围：region地区 platform平台
          //   'inclued': '', // 是否包含  1包含 2不包含
          //   'condition': '', // 发布条件
          //   'desp': ''// 备注
          // }
        ],
        grayUserNum: '', // 灰度人数
        numType: '0',
        expiryTime: '', // 灰度结束时间
        desp: '',
        releaseRuleId: '', // 常用规则
        // deviceListId: '', // 设备白名单
        whiteListId: ''// 用户白名单id
      },
      whiteOptions: [],
      releaseOptions: [],
      fileList: [],
      typeList: [],
      rules: {
        headerOperations: [
          { validator: checkHeader, trigger: 'blur' }
        ],
        releaseRuleId: [
          { validator: checkRadix, trigger: 'blur' }
        ],
        grayFlag: [
          { required: true }
        ],
        upgradeMode: [
          { required: true }
        ],
        upgradeDesp: [
          { required: true, message: '请输入升级描述', trigger: 'change' }
        ],
        releaseDestType: [
          { required: true }
        ],
        whiteListId: [
          { required: true, message: '请选择白名单', trigger: 'change' }
        ],
        expiryTime: [
          { required: true, message: '请选择发布时间', trigger: 'blur' }
        ],
        grayUserNum: [
          { required: true, message: '请输入灰度人数', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {
    'list.rule.regularRule'(newR, oldR) { // 常用规则
      if (this.list.rule.customRule && newR) {
        this.list.rule.regularRule = true
        this.list.rule.customRule = false
      }
      this.list.releaseRuleId = newR ? this.list.releaseRuleId : ''
    },
    'list.rule.customRule'(newC, oldC) {
      if (this.list.rule.regularRule && newC) {
        this.list.rule.customRule = true
        this.list.rule.regularRule = false
      }
      if (newC && this.list.headerOperations.length < 1) {
        this.addHeaderOption()
      }
    }

  },
  beforeMount() {
    this.whiteOptions = [{
      value: 'user',
      label: '用户',
      children: []
    },
      {
        value: 'device',
        label: '设备',
        children: []
      }]
    getTypeList({
      'beginPage': '1',
      'pageSize': '999'
    }).then(res => {
      this.typeList = res.context.list
      this.typeList.forEach(res => {
        res.platform = this.list.platformName
      })
      console.log(275, this.typeList)
    })
    getWhiteList({ type: 0 }).then(res => {
      if (res.code === '00') {
        const list = res.context.list
        list.forEach(i => {
          this.whiteOptions[0].children.push({
            value: i.id,
            label: i.name
          })
        })
      }
    })
    getWhiteList({ type: 1 }).then(res => {
      if (res.code === '00') {
        const list = res.context.list
        list.forEach(i => {
          this.whiteOptions[1].children.push({
            value: i.id,
            label: i.name
          })
        })
      }
    })
    getReleaseRuleList({}).then(res => {
      if (res.code === '00') {
        const list = res.context.list
        list.forEach(i => {
          this.releaseOptions.push({
            value: i.id,
            label: i.name
          })
          console.log(this.releaseOptions)
        })
      }
    })
  },
  mounted() {
    if (this.$route.query.data) {
      const params = JSON.parse(this.$route.query.data)
      this.list.packId = params.id
      this.list.version = params.version
      this.list.platformName = params.platform === '0' ? 'Android' : 'IOS'
    }
  },
  methods: {
    addHeaderOption() {
      this.list.headerOperations.push({
        'type': '',
        'operType': '',
        'value': '',
        'dictionaryList': []
        // 'desp': ''
      })
    },
    deleteHeaderOption(index) {
      this.list.headerOperations.splice(index, 1)
    },
    dictionaryTypeChange(index, value) {
      const params = { type: value }
      if (value !== 'city') {
        params.notPlatform = this.list.platformName === '0' ? 'IOS' : 'Android'
      }
      getDictionaryList(params).then(res => {
        if (res.code === '00') {
          this.list.headerOperations[index].dictionaryList = res.context.list
        }
      })
    },
    addNew() {
      console.log(this.list)
      const params = {}
      params.grayFlag = this.list.grayFlag
      params.pattern = this.list.upgradeMode
      params.patternHint = this.list.upgradeDesp
      params.desp = this.list.desp
      params.packId = this.list.packId
      if (this.list.grayFlag === '0') {
        params.deployType = this.list.releaseDestType
        params.desp = this.list.desp
        if (this.list.rule.regularRule) {
          params.releaseRuleId = this.list.releaseRuleId
        }
        if (this.list.rule.customRule) {
          params.releaseRuleItemList = this.list.headerOperations
        }
        if (this.list.releaseDestType === '0') { // 灰度白名单
          params.whiteListId = this.list.whiteListId[this.list.whiteListId.length - 1]
        }
        if (this.list.releaseDestType === '1') { // 灰度时间窗
          if (this.list.numType === '1') {
            params.grayUserNum = this.list.grayUserNum
          }
          params.expiryTime = this.list.expiryTime
        }
      }
      this.$refs.formAdd.validate((valid) => {
        if (valid) {
          getInstallTaskAdd(params).then(res => {
            if (res.code === '00') {
              this.$message({
                message: '新增发布任务成功！',
                type: 'success'
              })
              this.$router.go(-1)
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  background: #ffffff;
  margin: 24px;
}

.form-main {
  width: 700px;
  margin: 0 auto;
}

.form-row {
  margin-top: 20px;
}

.el-input.is-disabled .el-input__inner, .el-textarea.is-disabled .el-textarea__inner {
  border: 1px solid #E4E7ED !important;
}

.custom-table {
  font-size: 12px;
}

.addRow {
  width: 100px;
}

.remark-input {
  width: 400px;
}

</style>
