<template>
  <el-tabs v-model="activeName2" type="card" @tab-click="handleClick" class="sysSetting">
    <el-tab-pane label="企业信息" name="first">
      <div style="padding:15px; background-color: #fff;" v-loading="loading">
        <el-form
          :model="compnayInfoForm"
          :rules="rules"
          ref="compnayInfoForm"
          label-width="100px"
          style="width:590px; padding-top:30px;"
          class="demo-ruleForm"
        >
          <el-form-item label="公司标志" prop="logo" width="500px;">
            <upload_oss
              ref="upload"
              :headers="Xtoken"
              class="avatar-uploader"
              :action="'http://'+'integralsys.oss-cn-shenzhen.aliyuncs.com'"
              :show-file-list="true"
              :limit="1"
              :on-exceed="handleExceed"
              :on-preview="onFilePreView"
              :on-success="handleFilesSuccess"
              :before-upload="beforeFilesUpload"
              :on-remove="onFileRemove"
              :file-list="fileList"
            >
              <el-button
                @click="resetLogo"
                size="small"
                type="primary"
              >{{logoUrl?'重新上传公司Logo':'上传公司Logo'}}</el-button>
              <span style="color:#666;">建议尺寸(180*60)像素,图片格式(jpg、png、bmp、jpeg)</span>
            </upload_oss>
            <!-- <el-upload
              :headers="Xtoken"
              class="avatar-uploader"
              :action="serverdomain+'/integral.php/upload'"
              :show-file-list="true"
              :limit="1"
              :on-exceed="handleExceed"
              :on-success="handleFilesSuccessMini"
              :before-upload="beforeFilesUpload"
              :on-remove="onFileRemoveMini"
              :file-list="fileListMini"
            >
              <el-button size="small" type="primary">上传小logo</el-button>
            </el-upload>-->
          </el-form-item>
          <el-form-item label prop="logo">
            <upload_oss
              :headers="Xtoken"
              ref="uploadMini"
              class="avatar-uploader"
              :action="'http://'+'integralsys.oss-cn-shenzhen.aliyuncs.com'"
              :show-file-list="true"
              :limit="1"
              :on-preview="onFilePreView"
              :on-exceed="handleExceedMini"
              :on-success="handleFilesSuccessMini"
              :before-upload="beforeFilesUpload"
              :on-remove="onFileRemoveMini"
              :file-list="fileListMini"
            >
              <el-button
                @click="resetLogoMini"
                size="small"
                type="primary"
              >{{logoUrlMini?'重新上传缩略Logo':'上传缩略Logo'}}</el-button>
              <span style="color:#666;">建议尺寸(36*36)像素,图片格式(jpg、png、bmp、jpeg)</span>
            </upload_oss>
          </el-form-item>
          <el-form-item label="公司名称" prop="name">
            <el-input v-model="compnayInfoForm.name"></el-input>
          </el-form-item>

          <el-form-item label="联系人" prop="contacts">
            <el-input v-model="compnayInfoForm.contacts"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="compnayInfoForm.tel"></el-input>
          </el-form-item>

          <el-form-item label="所属行业" prop="industry">
            <el-select v-model="compnayInfoForm.industry" placeholder="请选择所属行业">
              <el-option label="IT/网络" value="IT/网络"></el-option>
              <el-option label="电子商务" value="电子商务"></el-option>
              <el-option label="制造业" value="制造业"></el-option>
              <el-option label="餐饮业" value="餐饮业"></el-option>
              <el-option label="金融" value="金融"></el-option>
              <el-option label="其它" value="其它"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="公司地址" prop="address">
            <el-input type="textarea" v-model="compnayInfoForm.address"></el-input>
          </el-form-item>
          <el-form-item label="系统员工数" v-if="sys_info">
                 <!-- <el-slider style="width:80%; display:inline-block;" :max="maxPeople" v-model="value" disabled></el-slider> -->
                 <el-progress style="width:80%; display:inline-block;" :text-inside="true" :stroke-width="18" :percentage="parseInt(100*value/maxPeople)"></el-progress>
                 <span style="vertical-align: top;color: rgb(102, 102, 102);">&nbsp;&nbsp; {{sys_info.employee_count>=maxPeople?maxPeople:sys_info.employee_count}} / {{maxPeople}}人</span>
          </el-form-item>
      
          <el-form-item>
            <el-button type="primary" :loading="send_site_info_loading" @click="send_site_info">保存信息</el-button>
            <el-button>重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-tab-pane>
    <el-tab-pane label="系统配置" name="second">
      <div style="padding:15px; background-color: #fff;">
        <SystemSettings></SystemSettings>
      </div>
    </el-tab-pane>

    <el-tab-pane label="自动积分" name="second2">
      <div style="padding:15px; padding-left:24px; padding-right:24px; background-color: #fff;">
        <PointAutoSetting ref="PointAutoSetting" @check="employee_check"></PointAutoSetting>
        <!-- totalCount -->
      </div>
    </el-tab-pane>
    <el-tab-pane label="系统日志">
      <div style="padding:15px; background-color: #fff;">
        <SystemLog></SystemLog>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import SystemSettings from './SystemSettings'
import PointAutoSetting from './PointAutoSetting'
import SystemLog from './SystemLog'
import qs from 'qs'
import { getToken } from '@/utils/auth'
import upload_oss from '@/views/upload_oss/upload'

export default {
  components: {
    PointAutoSetting,
    SystemSettings,
    SystemLog,
    upload_oss
  },
  data() {
    const validateTel = (rule, value, callback) => {
      const validValue = value
        ? value.replace(/\s/g, '').replace(/&nbsp;/gi, '')
        : value
      if (!validValue) {
        return callback(new Error('请填写手机号码'))
      }
      const pattern = /^1\d{10}$/
      if (pattern.test(value)) {
        callback()
      } else {
        return callback(new Error('无效的手机号，请重新输入'))
      }
    }
    return {
      sys_info: null,
      maxPeople: this.$store.getters.user_info.company_info.user_count_max,
      // employeeTotalCount: 0,
      value: 0,
      fileListMini: [],
      fileList: [],
      logoUrl: '',
      logoUrlMini: '',
      Xtoken: { 'X-Token': getToken() },
      loading: false,
      activeName2: 'first',
      compnayInfoForm: {
        name: '',
        industry: '',
        tel: '',
        contacts: '',
        address: ''
      },
      send_site_info_loading: false,
      rules: {
        name: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        contacts: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: validateTel, trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    resetLogo() {
      if (this.logoUrl) {
        this.logoUrl = ''
        this.$refs.upload.clearFiles()
      }
    },
    resetLogoMini() {
      if (this.logoUrlMini) {
        this.logoUrlMini = ''
        this.$refs.uploadMini.clearFiles()
      }
    },
    handleFilesSuccessMini(res, file) {
      this.logoUrlMini = res.url
    },
    onFileRemoveMini() {
      this.logoUrlMini = ''
    },
    handleFilesSuccess(res, file) {
      // this.$refs.upload.clearFiles()
      this.logoUrl = res.url
    },
    beforeFilesUpload(file) {
      const $ext_list =  ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']
      const $ext_name = file.name.split('.')[1]
      if ($ext_list.indexOf($ext_name) === -1) {
        this.$message.warning('不支持的文件格式')
        return false
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    handleExceedMini(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileListMini.length} 个文件`
      )
    },
    onFileRemove() {
      this.logoUrl = ''
    },
    employee_check(row) {
      console.log(row)
    },

    handleClick(tab, event) {
      console.log(tab, event)
    },
    get_sys_data() {
      const self = this
      // self.loading1 = true;
      const params = {}
      this.$http('get','/integral.php/ajax_request_common/get_sys_data')
        .then(response => {
          if (response.status == 200) {
            // self.loading1 = false;
            var jsonData = response.data
            try {
              self.sys_info = jsonData.data
              self.value = self.sys_info.employee_count >= self.maxPeople ? self.maxPeople : self.sys_info.employee_count
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    load_site_info() {
      this.loading = true
      const self = this
      this.$http('/integral.php/ajax_request_common/get_site_info').then(
        ret => {
          self.loading = false
          if (ret.status == '200') {
            const data = ret.data.data
            self.compnayInfoForm.name = data.name
            self.compnayInfoForm.industry = data.industry
            self.compnayInfoForm.tel = data.tel
            self.compnayInfoForm.contacts = data.contacts
            self.compnayInfoForm.address = data.address
          }
        }
      )
    },
    send_site_info() {
      var form = this.$refs['compnayInfoForm']
      var self = this
      if (this.logoUrl) {
        this.compnayInfoForm.logo_url = this.logoUrl
      }
      if (this.logoUrlMini) {
        this.compnayInfoForm.logo_min_url = this.logoUrlMini
      }
      form.validate(valid => {
        if (valid) {
          self.send_site_info_loading = true
          if (form) {
            self.$http('post','/integral.php/ajax_request_common/set_site_info',qs.stringify({ row: self.compnayInfoForm }),
                // headers: {
                //   'Content-Type': 'application/x-www-form-urlencoded'
                // }
              )
              .then(ret => {
                self.send_site_info_loading = false

                if (ret.status != '200') {
                  self.$message({
                    message: '网络错误',
                    type: 'error'
                  })
                } else {
                  if (ret.data.code == 1) {
                    form.clearValidate()
                    this.resetLogo()
                    this.resetLogoMini()
                    // 如果有logo上传 即刷新
                    this.$store.dispatch('GetUserInfo').then(res => {})
                    self.$message({
                      message: ret.data.msg,
                      type: 'success'
                    })
                  } else {
                    self.$message({
                      message: ret.data.msg,
                      type: 'error'
                    })
                  }
                }
              })
          }
        } else {
          return false
        }
      })
    },
    onFilePreView(file) {
      // 点击时查看文件
      window.open(file.response.url,'_blank')
    }
  },
  created() {
    const _this = this
    _this.load_site_info()
    this.get_sys_data()
  }
}
</script>
<style>
.sysSetting .el-slider__runway.disabled .el-slider__bar{
  background: #409EFF;
}
.sysSetting .el-slider__runway.disabled .el-slider__button {
    border-color: #409EFF;
}
</style>

