<template>
  <div class="editDialog">
    <el-dialog
      :visible.sync="dialogFormVisible" 
      :close-on-click-modal="close"
      :before-close="cancelRegister" 
      :title="registTitle"
      :top="top"
      width="700px">
      <el-form :inline="true" :model="form" :rules="rules" ref="form">
        <el-form-item label="英文名称" prop="nameEn">
          <el-input placeholder="请输入注册英文名称" v-model="form.nameEn" :disabled="!isReadonly"></el-input>
        </el-form-item>
        <el-form-item label="中文名称" prop="nameCn">
          <el-input placeholder="请输入注册中文名称" v-model="form.nameCn" :disabled="!isReadonly"></el-input>
          <div class="rule">填写规则：地区+功能+地图类型服务，如广东省河流分布3维地图服务</div>
        </el-form-item>
        <el-form-item  class="address" label="地址" prop="urls">
          <div class="changeAddress">
            <el-input type="textarea" resize="none" placeholder="请输入地址" v-model="form.urls" :disabled="!isReadonly">
            </el-input>
            <el-button class="addAddress" @click="addAddress" :disabled="!isReadonly">添加更多地址</el-button>
          </div>
        </el-form-item>
        
          <div class="moreAddress">
            <div class="moreAddressIn" v-for="(item,index) in form.moreAddress" :key="item.key">
             <el-form-item class="address" style="margin-left: 100px;" :prop="'moreAddress.' + index +'.addressValue'" :rules="moreAddressRules.address"> 
                <el-input type="textarea" resize="none" placeholder="请输入地址" v-model="item.addressValue" :disabled="!isReadonly"></el-input>
                <el-button @click="deleteAddress(index)" :disabled="!isReadonly">删除</el-button>
              </el-form-item>
            </div>
          </div>        
        <el-form-item label="服务类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择" :disabled="!isReadonly">
            <el-option
              :disabled="!isReadonly"
              v-for="item in options"
              :key="item.value"          
              :value="item.value">
            </el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="服务目录" prop="catalog">
          <el-cascader
            :disabled="!isReadonly"
            :options="form.options"
            :props="defaultProps"
            v-model="form.catalog"
            change-on-select
            @change="handleChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="是否公用">
          <el-radio class="radio" v-model="form.publicyn" label="1" :disabled="!isReadonly">是</el-radio>
          <el-radio class="radio" v-model="form.publicyn" label="0" :disabled="!isReadonly">否</el-radio>
        </el-form-item>
        <el-form-item label="服务描述">
          <el-input type="textarea" resize="none" placeholder="请输入服务描述" v-model="form.descriptions" :disabled="!isReadonly">
            </el-input>
        </el-form-item>
        <el-form-item label="是否通过" v-show="approve">
          <el-radio class="radio" v-model="form.auditstatus" label="1" :disabled="!isApproval">是</el-radio>
          <el-radio class="radio" v-model="form.auditstatus" label="-1" :disabled="!isApproval">否</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-show="detailShow">
        <el-button @click="cancelRegister">取 消</el-button>
        <el-button type="primary" @click="dialogSure('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Api from '@/api/index.js'

  export default { 
    name: 'EditDialog',
    props: {
      rowEditOnoff: { 
        type: Boolean,
        default: false
      },
      isReadonly: { 
        type: Boolean,
        default: true
      },
      approve: {
        type: Boolean,
        default: true
      },
      isApproval: {
        type: Boolean,
        default: false
      },
      detailShow: {
        type: Boolean,
        default: true
      },
      formData: { 
        type: Object,
        default: () => {}
      },
      top: { 
        type: String,
        default: '3%'
      },
      registTitle: {
        type: String,
        default: '注册服务'
      },
      close: {
        type: Boolean,
        default: false
      }
    },
    data () { 
      return { 
        // treeData: [], // 目录树
        dialogFormVisible: true,
        defaultProps: {
          children: 'childDirectoryinfos',
          label: 'nameCn',
          value: 'directoryid'
        },
        options: [{
          value: 'Map OGC WMS',
          label: 'Map OGC WMS'
        }, {
          value: 'Map OGC WFS',
          label: 'Map OGC WFS'
        }, {
          value: 'Map OGC WMTS',
          label: 'Map OGC WMTS'
        }, {
          value: 'SOAP',
          label: 'SOAP'
        }],
        value: '',
        form: {
          nameEn: '',
          nameCn: '',
          urls: '',
          type: '',
          catalog: [],
          options: [],
          serviceid: '',
          directoryid: '',
          publicyn: '0', // 表单内容
          auditstatus: '1', // 是否通过
          descriptions: '',
          moreAddress: [] // 添加更多地址
        },
        rules: {
          nameEn: [
            {required: true, message: '请输入英文名称', trigger: 'blur'},
            {validator: (rule, value, callback) => {
                if (value.length > 30 || value.length < 3) {
                  callback(new Error('长度必须为3~30个字符'))
                } else {
                  var reg = new RegExp('[^\a-\z\A-\Z0-9_]')
                  if (reg.test(value)) {
                    callback(new Error('只能填英文数字和下划线'))
                  } else {
                    callback()
                  }
                }
              },
              trigger: 'change'
            }
          ],
          nameCn: [
            {required: true, message: '请输入中文名称', trigger: 'blur'},
            {validator: (rule, value, callback) => {
                if (value.length > 15 || value.length < 3) {
                  callback(new Error('长度必须为3~15个字符'))
                } else {
                  var reg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
                  if (reg.test(value)) {
                    callback(new Error('不能含有特殊字符'))
                  } else {
                    callback()
                  }
                }
              },
              trigger: 'change'
            }
          ],
          urls: [
            {required: true, message: '请输入地址', trigger: 'blur'},
            {validator: (rule, value, callback) => {            
                if (value.length < 8) {
                  callback(new Error('长度不能少于8个字符'))
                } else {
                  var reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/
                  if (!reg.test(value)) {
                    callback(new Error('请输入合理的地址'))
                  } else {
                    callback()
                  }
                }
              },
              trigger: 'change'
            }
          ],       
          type: [
            {required: true, message: '请选择服务类型', trigger: 'blur'},
            {validator: (rule, value, callback) => {
                if (value.length === 0) {
                  callback(new Error('请选择服务类型'))
                } else {
                  callback()
                }             
              },
              trigger: 'blur'
            }
          ],
          catalog: [
            {required: true, message: '请选择目录', trigger: 'blur'},
            {validator: (rule, value, callback) => {
                if (value.length === 0 || value[0] === null) {
                  callback(new Error('请选择目录'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ]
        },
        moreAddressRules: {
          address: [
            {required: true, message: '请输入地址', trigger: 'blur'},
            {validator: (rule, value, callback) => {            
                if (value.length < 8) {
                  callback(new Error('长度不能少于8个字符'))
                } else {
                  var reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/
                  if (!reg.test(value)) {
                    callback(new Error('请输入合理的地址'))
                  } else {
                    callback()
                  }
                }
              },
              trigger: 'change'
            }
          ]
        }
      }
    },
         
    mounted () {
      this.initData()
      this.getCatalogTree()
    },
    methods: { 
      // 初始化数据
      initData () { 
        // 判断是注册还是修改
        if (this.rowEditOnoff) { // 修改
          this.showManageRegisterService()
        } else { // 注册
          this.form.nameEn = ''
          this.form.nameCn = ''
          this.form.urls = ''
          this.form.type = ''
          this.form.catalog = []
          this.form.publicyn = '0'
          this.form.descriptions = ''
          this.approve = false
        }
      }, 
      // 展示数据
      showManageRegisterService () {
        Api.showManageRegisterService(this.formData.serviceid)
        .then(data => {
          let datas = data.data
          if (data.status === 0) {
            this.form.nameEn = datas.nameEn
            this.form.nameCn = datas.nameCn 
            this.form.moreAddress = []
            var urlsArr = datas.urls.split(',')
            if (urlsArr.length !== 0) { 
              for (var i = 1; i < urlsArr.length; i++) { 
                this.form.moreAddress.push({addressValue: urlsArr[i]})
              }
            }
            this.form.urls = urlsArr[0]
            this.form.type = datas.type
            if (datas.directoryid !== null) {
              let len = parseInt(datas.directoryid.length / 4)
              for (let i = 1; i <= len; i++) {
                this.form.catalog.push(datas.directoryid.substring(0, i * 4))
              }
            }

            this.form.serviceid = datas.serviceid || ''
            this.form.publicyn = datas.publicyn
            this.form.descriptions = datas.descriptions || ''
            this.form.directoryid = datas.directoryid
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '请求数据失败'
          })
        })
      },
      // 确定
      dialogSure (formName) {
        if (this.isReadonly) {
          this.$refs[formName].validate((valid) => {
            if (valid) {           
              if (this.form.moreAddress.length !== 0) { 
                var addressArr = []
                for (var i = 0; i < this.form.moreAddress.length; i++) { 
                  addressArr.push(this.form.moreAddress[i].addressValue)
                }
                this.form.urls = this.form.urls + ',' + addressArr.join(',')
              }
              if (this.rowEditOnoff) { // 修改
                this.$emit('dialog-sure', [this.form, true])
              } else { // 注册
                this.$emit('dialog-sure', [this.form, false])
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          this.$emit('dialog-sure', [this.form, false])
        } 
      },
      // 取消
      cancelRegister () { 
        this.$emit('dialog-cancel')
      },
      // 添加更多地址
      addAddress () { 
        this.form.moreAddress.push({addressValue: ''})
      },
      // 删除地址
      deleteAddress (index) { 
        this.form.moreAddress.splice(index, 1)
      },
      // 获取服务目录
      getCatalogTree () {
        Api.getCatalogTree()
        .then(data => {
          let datas = data.data
          if (data.status === 0) {
            this.form.options = this.getChilds(datas)
          } else { 
            this.$message({
              type: 'warning',
              message: '获取目录树失败'
            })
          }
        }).catch(res => {
          this.treeLoading = false
          this.$message({
            type: 'error',
            message: '请求数据失败'
          })
        })
      },
      // 选择服务目录
      handleChange (value) {
        this.form.directoryid = value[value.length - 1]
        this.form.catalog = value
      },
      // 递归
      getChilds (data) {
        for (var i = 0; i < data.length; i++) {
           if (data[i].childDirectoryinfos.length !== 0) {
            this.getChilds(data[i].childDirectoryinfos)
          } else {
            delete data[i]['childDirectoryinfos']
          }
        }
        return data
      }
    } 
  }
</script>

<style lang="scss">
  .editDialog{ 
    .el-form-item__label { 
      width: 100px;
    }
    .dialog-content { 
      height: 500px;
    }
    .el-form-item {
      width: 100%;
    } 
    .el-form-item__content, .el-cascader, .el-select { 
      width: 400px;
    }
    .addAddress { 
      position: absolute;
      right: -114px;
      top: 8px;
      width: 106px;
      height: 38px;
      line-height: 38px;
      border: solid 1px #ccc;
      padding: 0 10px;
      border-radius: 4px;
      cursor: pointer;
    }
    .el-input-group__append { 
      cursor: pointer;
      &:hover{ 
        background: #e02f43;
        color: #fff;
        border-color: #e02f43;
      }
    }
    .catalogTree { 
      position: absolute;
      right: 110px;
      top: 240px;
      .radioTree {
        min-width: 180px;
        float: none;
        margin-right: 0;
        max-height: 182px;
        overflow-y: auto;
      }
    }
    
    /* .el-dialog__footer { 
      text-align: center;
    } */
    .moreAddressIn { 
      margin-top: 10px;
      position: relative;

      .el-textarea__inner {
        border-radius: 4px 0 0 4px;
      }

      .el-button {
        position: absolute;
        right: -45px;
        top: 0;
        padding: 19px 8px;
        border-radius: 0 4px 4px 0;
        border-left: none;
      }
    }
    .el-dialog__body { 
      padding: 20px 20px 0px 20px;
    }
  }
  .rule{
  margin-top: 6px;
  line-height: 18px;
  }
</style>
