<template>
  <el-dialog :visible.sync="visible" title="负责人" :close-on-click-modal="false" :close-on-press-escape="false" @closed="leaderClosed">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
      <el-form-item label="类别" label-width="110px" v-if="structLevel || structLevel === 0">
          {{ leaderCategoryCodeArr[structLevel].categoryName }}
      </el-form-item>
      <el-form-item label="名称" prop="name" label-width="110px">
          <el-input style="width:250px" v-model="dataForm.name" placeholder="负责任人名称"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender" label-width="110px">
        <el-select style="width:250px" v-model="dataForm.gender" clearable placeholder="性别">
          <el-option
            v-for="item in gender"
            :key="item.dictValue"
            :label="item.dictName"
            :value="item.dictValue"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系方式" prop="mobile" label-width="110px">
          <el-input style="width:250px" v-model="dataForm.mobile" placeholder="联系方式"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="interoduction" label-width="110px">
          <el-input style="width:250px" v-model="dataForm.interoduction" placeholder="简介"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatar" label-width="110px">
          <el-input style="width:250px" v-model="dataForm.avatar" placeholder="头像"></el-input>
      </el-form-item>
      <!-- <el-form-item label="头像" prop="avatar" label-width="110px">
        <el-upload class="avatar-uploader"
          :action="uploadUlr"
          :show-file-list="false"
          :on-success="(response, file, fileList) => handleImgSuccess('avatar', response, file, fileList)"
          :before-upload="beforeImgUpload">
          <img v-if="dataForm.avatar"
            :src="dataForm.avatar"
            style="width:70px;height:70px"
            class="function-icon">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item> -->
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { requestPost } from "@/js/dai/request";
export default {
  data () {
    return {
      uploadUlr: window.SITE_CONFIG['apiURL'] + '/oss/file/uploadqrcodeV2',
      visible: false,
      dataForm: {
        name: '',
        gender: '',
        mobile: '',
        interoduction: '',
        categoryCode: '',
        avatar: '',
        structReferenceId: '', // 动力主轴节点ID
        // customerId: localStorage.getItem('customerId'),
        leaderId: ''
      },
      leaderCategoryCodeArr: '', // 动力主轴节点级别
      gender: [
        { dictValue: '男', dictName: '男' },
        { dictValue: '女', dictName: '女' }
      ],
    }
  },

  props: {
    leaderVisible: {
      type: Boolean,
      default: false
    },
    axisStructId: {
      type: String,
      default: ''
    },
    leaderId: {
      type: String,
      default: ''
    },
    structLevel: {
      type: Number,
      default: null
    },
  },
  created(){
      this.getTagCategoryArr()
  },
  watch: {
      leaderVisible(newName){
          this.visible = newName
      },
      axisStructId (newName) {
        this.dataForm.structReferenceId = newName
      },
      leaderId(newName) {
        if (newName) {
          this.dataForm.leaderId = newName
          this.getInfo()
        }
      }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        gender: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        interoduction: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        avatar: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleImgSuccess (type, res, file) {
      if (res.code === 0 && res.msg === 'success') {

        console.log('type', type)
        console.log('res.data.url', res.data.url)

      } else {
        this.$message.error(res.msg)
      }
    },
    beforeImgUpload (file) {
      // const isPNG = file.type === 'image/png'
      const isLt1M = file.size / 1024 / 1024 < 1

      // if (!isPNG) {
      //   this.$message.error('上传图片只能是 PNG 格式!')
      // }
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
      }
      // return isPNG && isLt1M
      return isLt1M
    },
    // 获取信息
    async getInfo () {
      // this.$http.get(`/pli/power/axisLeader/getLeaderDetai/${this.dataForm.structReferenceId}`).then(({ data: res }) => {
      //   if (res.code !== 0) {
      //     return this.$message.error(res.msg)
      //   }
      //   this.dataForm = {
      //     ...this.dataForm,
      //     ...res.data
      //   }
      // }).catch(() => {})
      const url = `/pli/power/axisLeader/getLeaderDetail/${this.dataForm.structReferenceId}`
      const { data, code, msg } = await requestPost(url)
      if (code === 0) {
          this.dataForm = {
            ...this.dataForm,
            ...data
          }
      } else {
          this.$message.error(msg)
      }
    },
    // 表单提交
     dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if (this.leaderId) {
          this.updateLeader()
        } else {
          this.addLeader()
        }
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    leaderClosed () {
      this.visible = false
      this.$emit('refreshDataListleader')
    },
    async addLeader() {
      this.dataForm.categoryCode = this.leaderCategoryCodeArr[this.structLevel].categoryCode
      const url = '/pli/power/axisLeader/save/'
      const { data, code, msg } = await requestPost(url, this.dataForm)
      if (code === 0) {
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataListleader')
            }
          })
      } else {
          this.$message.error(msg)
      }
    },
    async updateLeader() {
      this.dataForm.categoryCode = this.leaderCategoryCodeArr[this.structLevel].categoryCode
      const url = '/pli/power/axisLeader/update'
      const { data, code, msg } = await requestPost(url, this.dataForm)
      if (code === 0) {
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataListleader')
            }
          })
      } else {
          this.$message.error(msg)
      }
    },
    // 获取动力主轴标签
    async getTagCategoryArr(){
      const url = '/pli/power/axisTag/listSimple/leader'
      let params = {}
      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.leaderCategoryCodeArr = data
      } else {
          this.$message.error(msg)
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader {
  ::v-deep
  .el-upload {
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar {
    width: 70px;
    height: 70px;
    display: block;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 70px;
    height: 70px;
    line-height: 70px;
    text-align: center;
  }
}
</style>
