<template>
  <div class="create-container">
    <div class="create-body">
      <div class="title">添加机构</div>
      <el-form v-loading="loading" :model="agency" :rules="rules" ref="agency" label-width="12%" class="demo-report">
        <el-form-item label="机构名称" prop="name">
          <el-input size="small" v-if="isModifyMode" v-model="agency.name"></el-input>
          <!--<span v-if="!isModifyMode">{{agency.name}}</span>-->
        </el-form-item>
        <el-form-item size="small" label="机构电话" prop="mobile">
          <el-input v-if="isModifyMode" v-model="agency.mobile"></el-input>
          <!--<span v-if="!isModifyMode">{{agency.name}}</span>-->
        </el-form-item>
        <el-form-item size="small" label="机构邮箱" prop="email">
          <el-input v-if="isModifyMode" v-model="agency.email"></el-input>
          <!--<span v-if="!isModifyMode">{{agency.name}}</span>-->
        </el-form-item>
        <el-form-item size="small" label="银行卡账户" prop="bankAccount">
          <el-input v-if="isModifyMode" v-model="agency.bankAccount"></el-input>
          <!--<span v-if="!isModifyMode">{{agency.bankAccount}}</span>-->
        </el-form-item>
        <el-form-item size="small" label="地址" prop="address">
          <el-input v-if="isModifyMode" v-model="agency.address"></el-input>
          <!--<span v-if="!isModifyMode">{{agency.address}}</span>-->
        </el-form-item>
        <el-form-item label="测评机构能力" prop="evaluationAgencyAbilityList">
          <el-checkbox-group v-if="isModifyMode" v-model="agency.evaluationAgencyAbilityList">
            <span v-for="(item,index) in serviceTypes" :key="index">
              <el-checkbox :label="item"
                           name="evaluationAgencyAbilityList">{{item}}&nbsp;&nbsp;&nbsp;&nbsp;</el-checkbox>
            </span>
          </el-checkbox-group>
          <!--<span v-if="!isModifyMode">{{agency.ability}}</span>-->
        </el-form-item>
        <el-form-item label="测评机构资源" prop="resource">
          <span v-for="item in agency.evaluationAgencyResourceList" :key="item.id">
            资源类型：&nbsp;<el-select size="small" v-model="item.type" placeholder="请选择" style="width: 15%;margin-bottom: 10px"
                                  :value="item.type">
              <el-option
                v-for="item in resourceTypes"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            资源名称：&nbsp;<el-input size="small" v-model="item.name" style="width: 15%"></el-input>
            总量：&nbsp;<el-input-number size="small" :min="0" v-model="item.totalNum"></el-input-number>
            可用数量：&nbsp;<el-input-number size="small" :min="0" :max="item.totalNum" v-model="item.availableNum"></el-input-number>
            <el-button size="small" type="danger" icon="el-icon-delete" @click="removeAgencyResource(item.id)"></el-button>
            <br/>
          </span>
          <el-button  type="primary" icon="el-icon-circle-plus" plain size="mini" @click="addAgencyResource">添加资源
          </el-button>
        </el-form-item>
        <el-form-item prop="file" label="机构logo">
          <el-upload
            v-if="isModifyMode"
            class="avatar-uploader"
            :show-file-list="false"
            action="https://jsonplaceholder.typicode.com/posts/"
            :before-upload="beforeFileUpload"
            :http-request="uploadFile"
            :file-list="agency.photo"
          >
            <img v-if="agency.photoUrl" :src="agency.photoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <!--<div class="el-upload__text">-->
            <!--将文件拖到此处，或-->
            <!--<em>点击上传</em>-->
            <!--</div>-->
            <!--<div class="el-upload__tip" slot="tip">请上传报告文件</div>-->
          </el-upload>
          <!--<div v-if="!isModifyMode">-->
          <!--<span v-if="agency.photo==null">暂无文件</span>-->
          <!--<a :href="agency.photo" v-if="agency.photo!=null"><i class="fa fa-file-text-o"></i>-->
          <!--{{agency.photo}}</a>-->
          <!--</div>-->
        </el-form-item>

        <!--<el-form-item v-if="!isModifyMode">-->
        <!--<div class="btn btn-medium btn-info" @click="modifyInfo()">修改</div>-->
        <!--<div class="btn btn-medium" @click="cancelModify()">返回</div>-->
        <!--</el-form-item>-->
        <el-form-item v-if="isModifyMode">
          <div class="btn btn-primary btn-info" @click="submitInfo()">提交</div>
          <!--<div class="btn btn-primary" @click="cancelModify()">取消</div>-->
        </el-form-item>
      </el-form>
      <el-dialog
        title="测评机构添加成功"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleDialogClose"
        center>
        <span>
          <el-card class="box-card" shadow="always">
            <div slot="header" class="clearfix">
              <span>您添加的机构信息</span>
            </div>
            <div class="text item">
              <ul style="list-style-type:none">
                <li>机构名称：{{ agency.name }}</li>
                <li>机构电话：{{ agency.mobile }}</li>
                <li>银行卡账户：{{ agency.bankAccount }}</li>
                <li>地址：{{ agency.address }}</li>
                <li>邮箱：{{ agency.email }}</li>
              </ul>
            </div>
          </el-card>
          <br/>
          <el-card class="box-card" shadow="always">
            <div class="text item">
              您可以使用以下的账号密码登录系统:
              <ul style="list-style-type:none">
                <li>账号：{{ agency.email }}</li>
                <li>密码：{{ agency.mobile }}</li>
              </ul>
              也可以使用手机号{{ agency.mobile }}验证码登录
            </div>
          </el-card>
        </span>
        <span slot="footer" class="dialog-footer">
    <el-button @click="handleDialogClose">返 回</el-button>
    <el-button type="primary" @click="toLogin">去登录</el-button>
  </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Http from '@/js/http'
import Apis from '@/js/api'
import {notify} from '@/constants/index'
import {getAllAbilities, getAllAgencyResourceTypes, storageGet} from '@/js/index'

export default {
  name: 'AgencyAdd',
  data () {
    return {
      user: {},
      userId: 0,
      loading: false,
      isModifyMode: true,
      dialogVisible: false,
      serviceTypes: [],
      resourceTypes: [],
      agency: {
        mobile: '',
        email: '',
        name: '',
        bankAccount: '',
        address: '',
        evaluationAgencyAbilityList: [],
        evaluationAgencyResourceList: [
          {
            id: 0,
            type: '',
            name: '',
            totalNum: 0,
            availableNum: 0,
          }
        ],
        professionalsCount: 0,
        professionalsFreeCount: 0,
        serversCount: 0,
        serversFreeCount: 0,
        devicesCount: 0,
        devicesFreeCount: 0,
        photo: [],
        photoUrl: '',
        password: '',
        username: '',
      },
      rules: {
        name: [
          {required: true, message: '请输入测评机构名称', trigger: 'blur'}
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'}
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'}
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        bankAccount: [
          {required: true, message: '请输入银行卡号', trigger: 'blur'}
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        address: [
          {required: true, message: '请输入机构地址', trigger: 'blur'}
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        evaluationAgencyAbilityList: [
          {type: 'array', required: true, message: '请至少选择一个机构能力', trigger: 'change'}
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        evaluationAgencyResourceList: [
          {
            validator: (rule, value, callback) => {
              var isError = false
              if (value == null || value.length == 0){
                callback(new Error('机构资源不可为空'))
              } else {
                for (var i = 0; i < value.length; i++) {
                  if (value[i].name == '') {
                    isError = true
                    break
                  }
                }
              }
              if (isError) {
                callback(new Error('资源名称不可为空'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          },
        ],
      },
      tableData: [{
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄'
      }, {
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄'
      }, {
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1516 弄'
      }]
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    //初始化
    init () {
      this.setServiceTypes()
      this.setResourceTypes()
      this.setUserInfo()
    },
    //加载数据
    loadData: function () {
    },
    //表单进入可编辑状态，可修改表单，不再使用
    modifyInfo () {
      this.isModifyMode = true
    },
    //提交表单
    submitInfo () {
      //this.showDialog()
      this.showLoading()
      const newAgency = {
        mobile: this.agency.mobile,
        evaluationAgencyName: this.agency.name,
        bankAccount: this.agency.bankAccount,
        address: this.agency.address,
        evaluationAgencyAbilityList: this.agency.evaluationAgencyAbilityList,
        evaluationAgencyResourceList: this.agency.evaluationAgencyResourceList,
        agencyPhoto: this.agency.photoUrl,
        email: this.agency.email
      }
      Http.post(Apis.USER.ADD_AGENCY, newAgency).then((res) => {
        this.hideLoading()
        console.log(res)
        // console.log(res.data)
        //res = res.data
        this.agency.password = res.userVO.password
        this.agency.username = res.userVO.userName
        this.agency.mobile = res.userVO.mobile
        this.showDialog()
      }).catch(error => {
        this.hideLoading()
        notify('error', error.data)
      })
    },
    //取消修改表单，表单进入不可编辑状态，不再使用
    cancelModify () {
      this.isModifyMode = false
    },
    //上传文件时移除文件的响应函数
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    //添加文件时的响应函数
    handleExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
          } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    //移除文件前的响应函数
    beforeRemove (file, fileList) {
      //return this.$confirm(`确定移除 ${file.name}？`)
    },
    //文件上传前的响应函数
    beforeFileUpload () {
    },
    //上传文件，此处为上传图片
    uploadFile (param) {
      const formData = new FormData()
      let config = {
        //添加请求头
        headers: {'Content-Type': 'multipart/form-data'},
      }
      formData.append('file', param.file)
      //console.log(JSON.parse(this.user).userVO)
      Http.upload(Apis.FILE.UPLOAD_IMAGE.replace('{userId}', this.user.userVO.id), formData, config).then((res) => {
        this.agency.photoUrl = res.data
        console.log(res.data)
        notify('success', '上传成功')
      }).catch(error => {
        notify('error', error.data)
      })
    },
    //关闭对话框时的响应函数
    handleDialogClose (done) {
      this.$confirm('确认退出？退出前请记录下登录账号和密码，否则无法找回！！！')
        .then(_ => {
          //done()
          this.hideDialog()
        })
        .catch(_ => {
        })
    },
    //弹出对话框
    showDialog () {
      this.dialogVisible = true
    },
    //隐藏对话框
    hideDialog () {
      this.dialogVisible = false
      this.resetForm()
    },
    //TODO 跳转到登录页面
    toLogin () {
      this.hideDialog()
      this.$router.push({
        name: 'Home',
        // params: {projectId: projectId, taskId: taskId}
      })
    },
    //重置表单
    resetForm () {
      this.agency = {
        mobile: '',
        email: '',
        name: '',
        bankAccount: '',
        address: '',
        evaluationAgencyAbilityList: '',
        evaluationAgencyResourceList: '',
        photo: [],
        photoUrl: '',
        password: '',
        username: '',
      }
    },
    //设置服务类型
    setServiceTypes () {
      this.serviceTypes = getAllAbilities()
    },
    //添加一项测评机构资源
    addAgencyResource () {
      const tmpResource = {
        id: this.agency.evaluationAgencyResourceList.length,
        type: this.resourceTypes[0],
        name: '',
        totalNum: 0,
        availableNum: 0,
      }
      this.agency.evaluationAgencyResourceList.push(tmpResource)
    },
    //删除一项测评机构资源
    removeAgencyResource (id) {
      this.agency.evaluationAgencyResourceList.splice(id, 1)
      for (var i = 0; i < this.agency.evaluationAgencyResourceList.length; i++) {
        this.agency.evaluationAgencyResourceList[i].id = i
      }
    },
    //设置测评机构资源类型
    setResourceTypes () {
      this.resourceTypes = getAllAgencyResourceTypes()
    },
    //检测测评机构资源填写是否有效
    checkAgencyResourceVaild () {
      if (this.agency.evaluationAgencyResourceList.length === 0) {
        return true
      }
      for (var i = 0; i < this.agency.evaluationAgencyResourceList.length; i++) {
        const item = this.agency.evaluationAgencyResourceList[i]
        if (item.type === '') {
          notify('error', '资源类型不能为空')
          return false
        }
        if (item.name === '') {
          notify('error', '资源名称不能为空')
          return false
        }
        if (item.totalNum < item.availableNum) {
          notify('error', '资源总数量不能低于可用数量')
          return false
        }
      }
      return true
    },
    //获取用户信息
    setUserInfo () {
      this.user = storageGet('user')
    },
    //显示loading
    showLoading () {
      this.loading = true
    },
    //隐藏loading
    hideLoading () {
      this.loading = false
    }
  },
  created: function () {
  }
}
</script>

<style scoped>
  .el-radio {
    margin: 10px 20px 10px 0;
  }

  .el-form-item /deep/ .el-tabs__content {
    max-height: 120px !important;
    overflow: auto;
  }

  .el-row {
    margin-bottom: 10px;
  }

  .el-input {
    width: 400px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .el-input-number {
    width: 150px;
  }
</style>
