<template>
  <manager-dialog
    :title="title"
    icon="el-icon-plus"
    :visible.sync="dialogVisible"
    width="50%"
    :close-on-click-modal="false"
    class="arrangementObjectManagementDialog"
    @opened="open"
    @close="close"
  >
    <el-form
      ref="form"
      v-loading="loading"
      :rules="command === 'detail' ? null : rules"
      :model="form"
      size="small"
      label-width="120px"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="基础信息" name="first">
          <el-row>
            <el-col :span="12">
              <el-form-item label="编排对象名称:" prop="layoutName">
                <el-input
                  v-if="command !== 'detail'"
                  v-model="form.layoutName"
                  placeholder="请输入"
                /><span v-else>{{ form.layoutName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编排对象编码:" prop="layoutCode">
                <el-input
                  v-if="command !== 'detail'"
                  v-model="form.layoutCode"
                  placeholder="请输入"
                /><span v-else>{{ form.layoutCode }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="业务类型:" prop="layoutType">
                <el-select
                  v-if="command !== 'detail'"
                  v-model="form.layoutType"
                  placeholder="请输入"
                >
                  <el-option label="费用" value="1" />
                  <el-option label="资料" value="2" />
                  <el-option label="清单" value="3" /> </el-select>
                <span v-else>{{ form.layoutType==1?'费用':
                  form.layoutType==2?'资料':'清单' }}</span>
              </el-form-item></el-col>

            <el-col :span="12">
              <el-form-item label="归属系统:" prop="businessId">
                <manager-tree-select
                  v-if="command !== 'detail'"
                  ref="business"
                  v-model="form.businessId"
                  :data="staticsData.businessTree"
                  :defaultProps="{
                    label: 'label',
                    children: 'children',
                    disabled: 'specTag'
                  }"
                  @clear="form.businessId = []; $refs.business.filterText = ''"
                />
                <span v-else>{{ form.businessName }}</span>
              </el-form-item></el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="标签:" prop="layoutLabel">
                <el-select
                  v-if="command !== 'detail'"
                  v-model="form.layoutLabel"
                  placeholder="请输入"
                >
                  <el-option
                    v-for="item in staticsData.layoutLabelList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  /> </el-select><span v-else>{{ form.layoutLabel|toCase(statics.layoutLabelList,'value', 'label') }}</span>
              </el-form-item></el-col>

            <el-col :span="24">
              <el-form-item
                label="图标:"
                prop="layoutIcon"
                :rules="[
                  {
                    required: command === 'add' ? true : false,
                    message: '请选择图标',
                    trigger: 'blur',
                  },
                ]"
              >
                <upload-button
                  v-if="command !== 'detail'"
                  ref="uploadIcon"
                  accept=".jpg, .png"
                  @change="onChartChange"
                  @remove="form.layoutIcon = []"
                />
                <span
                  v-if="command!=='add'"
                  style="cursor: pointer"
                  @click="download(baseUrl + '/analyze/' + form.layoutIcon)"
                >{{ getFileName(form.layoutIcon) }}</span>
                <span />
              </el-form-item></el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="后端地址:" prop="interfaceAddress">
                <el-input
                  v-if="command !== 'detail'"
                  v-model="form.interfaceAddress"
                  placeholder="请输入ip:端口,例1.1.1.1:8080"
                /><span v-else>{{ form.interfaceAddress }}</span>
              </el-form-item></el-col>

            <el-col :span="24">
              <el-form-item label="描述:" prop="layoutDesc">
                <el-input
                  v-if="command !== 'detail'"
                  v-model="form.layoutDesc"
                  placeholder="请输入"
                /><span v-else>{{ form.layoutDesc }}</span>
              </el-form-item></el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="导入接口配置信息" name="second">
          <el-form-item
            label="接口文件:"
            prop="interfaceFile"
            :rules="[
              {
                required: command === 'add' ? true : false,
                message: '请选择接口文件',
                trigger: 'blur',
              },
            ]"
          >
            <upload-button
              v-if="command !== 'detail'"
              ref="uploadFile"
              accept=".json"
              @change="onFileChange"
              @remove="form.interfaceFile = []"
            /><span
              v-if="command!=='add'"
              style="cursor: pointer"
              @click="download(baseUrl + '/analyze/' + form.interfaceFile)"
            >{{ getFileName(form.interfaceFile) }}</span>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="编辑策略" name="third">
          <el-row>
            <el-col :span="24"><el-form-item label="超时(秒):" prop="overTime">
              <el-input-number
                v-if="command !== 'detail'"
                v-model="form.overTime"
                :min="0"
                placeholder="请输入"
              /><span v-else>{{ form.overTime }}</span>
            </el-form-item></el-col>
            <el-col :span="12"><el-form-item label="流控类型:" prop="flowControlType">
              <el-select
                v-if="command !== 'detail'"
                v-model="form.flowControlType"
                placeholder="请选择"
              ><el-option label="普通流控" value="1" /></el-select>
              <span v-else>{{ form.flowControlType==1?'普通流控':'其它流控' }}</span>
            </el-form-item></el-col>
            <el-col :span="12"><el-form-item label="流控周期:" prop="flowControlCircle">
              <el-select
                v-if="command !== 'detail'"
                v-model="form.flowControlCircle"
                placeholder="请选择"
              ><el-option label="分钟" value="1" /><el-option
                label="小时"
                value="2"
              /></el-select><span v-else>{{ form.flowControlCircle==1?'分钟':'小时' }}</span>
            </el-form-item></el-col>
            <el-col :span="12"><el-form-item label="流控次数:" prop="flowControlCount">
              <el-input-number
                v-if="command !== 'detail'"
                v-model="form.flowControlCount"
                :min="0"
                placeholder="请输入"
              /><span v-else>{{ form.flowControlCount }}</span>
            </el-form-item></el-col>
            <el-col :span="24"><el-form-item label="安全类型:" prop="safeType">
              <el-select
                v-if="command !== 'detail'"
                v-model="form.safeType"
                placeholder="请输入"
              >
                <el-option label="明文" value="1" />
                <el-option label="RSA" value="2" />
                <el-option label="MD5" value="3" />
              </el-select>
              <span v-else>{{ form.safeType==1?'明文':form.safeType==2?'RSA':'MD5' }}</span>
            </el-form-item></el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">{{
        command === 'detail' ? '关闭' : '取消'
      }}</el-button>
      <el-button v-if="command !== 'detail'" @click="resetForm">重置</el-button>
      <el-button
        v-if="command !== 'detail'"
        type="primary"
        @click="submit"
      >提交</el-button>
    </span>
  </manager-dialog>
</template>

<script>
import UploadButton from '@ability/components/UploadButton/src'
import { addObject,
  editObject,
  uploadIcon,
  uploadFile } from '../api/arrangementObjectManagement'
import { baseUrl } from '@ability/utils/request'
export default {
  name: 'Dialog',
  components: { UploadButton },
  props: {
    command: String,
    data: Object,
    row: Object,
    statics: Object
  },
  data() {
    const validateTree = (rule, value, callback) => {
      if (value.length > 1) {
        callback(new Error('最多只能选择一个业务系统'))
      } else {
        callback()
      }
    }
    return {
      activeName: 'first',
      baseUrl: baseUrl,
      id: null,
      dialogVisible: false,
      loading: false,
      staticsData: this.statics,
      form: {
        layoutName: null, // 编排对象名称
        layoutCode: null, // 编排对象编码
        layoutType: null, // 业务类型
        businessId: [], // 归属系统
        layoutLabel: null, // 标签
        interfaceAddress: null, // 后端地址
        layoutIcon: [], // 图标
        layoutDesc: null, // 描述
        interfaceFile: [], // 接口文件
        overTime: null, // 超时
        flowControlType: '1', // 流控类型
        flowControlCount: null, // 流控次数
        flowControlCircle: '1', // 流控周期
        safeType: null // 安全类型
      },
      rules: {
        layoutName: [
          { required: true, message: '请选择编排对象名称', trigger: 'blur' }
        ],
        layoutCode: [
          { required: true, message: '请输入编排对象编码', trigger: 'blur' }
        ],
        // layoutType: [
        //   { required: true, message: '请选择业务类型', trigger: 'change' }
        // ],
        // businessId: [
        //   { required: true, message: '请选择归属系统', trigger: 'change' },
        //   { validator: validateTree, trigger: 'blur' }  
        // ],
        // layoutLabel: [
        //   { required: true, message: '请选择标签', trigger: 'change' }
        // ],
        interfaceAddress: [
          { required: true, message: '请输入后端地址', trigger: 'blur' }
        ],
        // layoutDesc: [
        //   { required: true, message: '请输入描述', trigger: 'blur' }
        // ],
        overTime: [
          { required: true, message: '请选择超时(秒)', trigger: 'blur' }
        ],
        flowControlType: [
          { required: true, message: '请选择流控类型', trigger: 'change' }
        ],
        flowControlCount: [
          { required: true, message: '请选择流控次数', trigger: 'blur' }
        ],
        flowControlCircle: [
          { required: true, message: '请选择流控周期', trigger: 'change' }
        ],
        safeType: [
          { required: true, message: '请选择安全类型', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.command === 'add'
        ? '新增'
        : this.command === 'modify'
          ? '修改'
          : '查看'
    }
  },
  methods: {
    download(url) {
      let link = document.createElement('a')
      fetch(url).then(res => res.blob()).then(blob => {
        link.href = URL.createObjectURL(blob)
        link.download = ''
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    },
    close() {
      if (this.$refs.uploadIcon) this.$refs.uploadIcon.fileList = []
      if (this.$refs.uploadFile) this.$refs.uploadFile.fileList = []
      if (this.$refs.business) this.$refs.business.filterText = ''
      this.$refs.form.resetFields()
    },
    open() {
      this.activeName = 'first'
      this.loading = true
      this.$refs.form.resetFields()
      if (this.command === 'add') {
        this.form = this.$options.data().form
      } else if (this.command === 'modify') {
        const form = JSON.parse(JSON.stringify(this.row))
        form.businessId = [form.businessId]
        form.createUser = undefined
        form.createTime = undefined
        Object.assign(this.form, form)
        this.$refs.business.setCheckedKeys(form.businessId)
      } else {
        Object.assign(this.form, this.row)
      }
      this.loading = false
    },
    getFileName(path) {
      if (typeof path === 'string') {
        const fileName = path.split('/')
        return fileName.pop()
      }
    },
    submit() {
      const layouobjectInfo = JSON.parse(JSON.stringify(this.form))
      layouobjectInfo.businessId = layouobjectInfo.businessId[0]
      this.$refs.form.validate((valid, fields) => {
        if (valid) {
          if (this.command === 'add') {
            addObject({
              layouobjectInfo
            })
              .then((resp) => {
                if (resp.data.returnCode == '0') {
                  this.$message.success(resp.data.returnMsg)
                  this.$emit('success')
                  this.dialogVisible = false
                }
              })
          } else {
            editObject({
              layouobjectInfo
            })
              .then((resp) => {
                if (resp.data.returnCode == '0') {
                  this.$message.success(resp.data.returnMsg)
                  this.$emit('success')
                  this.dialogVisible = false
                }
              })
          }
        } else {
          let first = ['layoutName', 'layoutCode', 'layoutType', 'businessId', 'layoutLabel', 'layoutIcon', 'interfaceAddress', 'layoutDesc']
          let second = ['interfaceFile']
          let third = ['overTime', 'flowControlType', 'flowControlCircle', 'flowControlCount', 'safeType']
          let keys = Object.keys(fields)
          for(let i = 0; i < keys.length; i++) {
            if (first.includes(keys[i])) {
              this.activeName = 'first'
              break
            } else if (second.includes(keys[i])) {
              this.activeName = 'second'
              break
            } else if (third.includes(keys[i])) {
              this.activeName = 'third'
              break
            }
          }
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
    },
    onChartChange(fileList) {
      if (!fileList || !fileList.length) return
      const formData = new FormData()
      formData.set('file', fileList[0].raw)
      uploadIcon(formData)
        .then((resp) => {
          if (resp.data.returnCode == '0') {
            this.form.layoutIcon = resp.data.data
            this.$message.success(resp.data.returnMsg)
            this.$refs.form.clearValidate('layoutIcon')
          } else {
            this.$refs.uploadFile.clearFileList()
          }
        })
        .catch(err => {
          console.log('拿到异常', err)
          this.$message.warning(err)
          this.$refs.uploadFile.clearFileList()
        })
    },
    onFileChange(fileList) {
      if (!fileList || !fileList.length) return
      const formData = new FormData()
      formData.set('file', fileList[0].raw)
      uploadFile(formData)
        .then((resp) => {
          if (resp.data.returnCode == '0') {
            this.form.interfaceFile = resp.data.data
            this.$message.success(resp.data.returnMsg)
            this.$refs.form.clearValidate('interfaceFile')
          } else {
            this.$refs.uploadFile.clearFileList()
          }
        })
        .catch(err => {
          this.$message.warning(err)
          this.$refs.uploadFile.clearFileList()
        })
    }
  }
}
</script>

<style lang="scss" scoped>
  .arrangementObjectManagementDialog {
    ::v-deep .el-tabs__content {
      overflow: visible;
    }
    ::v-deep .dropdownCls {
      min-width: auto;
    }
    ::v-deep  .el-tree > .el-tree-node{
      min-width:100%;
      display: inline-block;
    }
  }
</style>

<style >

</style>