<template>
  <div class="configPage">
    <h1>项目配置</h1>
    <!-- <div class="bg"></div> -->
    <div class="content">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="服务器配置" name="server">
          <el-form
            :model="form"
            ref="form">
            <el-form-item
              class="is-require"
              verify
              label="服务器地址"
              prop="serverUrl">
              <el-input
                placeholder=""
                v-model="form.serverUrl">
              </el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="打印配置" name="print">
          <el-form>
            <el-form-item
              :label="`门票打印机`"
              prop="printer">
              <el-select
                v-model="form.defaultPrinter"
                style="width:100%">
                <el-option
                  v-for="item in printers"
                  :key="item.name"
                  :value="item.name"
                  :label="item.name"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              :label="`小票打印机`"
              prop="printer">
              <el-select
                v-model="form.defaultSmallTicketPrinter"
                style="width:100%">
                <el-option
                  v-for="item in printers"
                  :key="item.name"
                  :value="item.name"
                  :label="item.name"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              label="自动打印门票开关"
              prop="printer">
              <el-switch
                v-model="form.autoPrint"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
            <el-form-item
              label="售票快捷键支持"
              prop="quickSupport">
              <el-switch
                v-model="form.quickSupport"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>

            <el-form-item
              label="显示景点便签（售票界面）"
              prop="showScenicTag">
              <el-switch
                v-model="form.showScenicTag"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>

            <el-form-item
              label="售票初始数量"
              prop="initNum">
              <el-select
                v-model="form.initNum"
                style="width:100%">
                <el-option
                  label="空"
                  value="空"></el-option>
                <el-option
                  label="1"
                  :value="1"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              label="默认支付方式"
              prop="initNum">
              <el-select
                v-model="form.defaultPayWay"
                style="width:100%">
                <el-option
                  label="无"
                  value=""></el-option>
                <el-option
                  v-for="(item,index) in payChannelOptions"
                  :key="index"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              label="IC卡补齐长度( 此处设置优先级高于：系统管理->参数配置->IC卡补齐长度。0为不补齐 )"
              prop="ICCardLength">
              <el-input
                style="width:100%"
                v-model.number="form.ICCardLength"
                size="normal"
                :min="0"
                :step="1"
                :controls="true"
                controls-position="both">
              </el-input>
            </el-form-item>

            <el-form-item
              label="人脸识别类型"
              prop="initNum">
              <el-select
                v-model="form.faceApi"
                style="width:100%">
                <el-option
                  label="faceApi"
                  value="faceApi"></el-option>
                <el-option
                  label="Tracking"
                  value="tracking"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              v-if="form.faceApi==='faceApi'"
              label="人脸识别模型"
              prop="faceModel">
              <el-select
                v-model="form.faceModel"
                style="width:100%">
                <el-option
                  label="ssdMobilenetv1"
                  value="ssdMobilenetv1"></el-option>
                <el-option
                  label="mtcnn"
                  value="mtcnn"></el-option>
                <el-option
                  label="tinyFaceDetector"
                  value="tinyFaceDetector"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="POS机终端设置" name="pos">
          <el-form>
            <el-form-item label="款台号">
              <el-input
                :disabled="scenicName==='狼山景区'||scenicName==='军山景区'"
                v-model="form.termId"></el-input>
            </el-form-item>

            <el-form-item label="支付客户端路径">
              <el-button
                type="info"
                @click="selectFolder('softposPath')">
                选择目录
              </el-button>
              <el-link
                @click="openFolder"
                type="success"
                style="margin-left:20px">
                已选择：{{ form.softposPath }}
              </el-link>
            </el-form-item>

            <el-form-item label="Pos退款方式">
              <el-select v-model="form.refundWay">
                <el-option
                  label="退货"
                  value="refunds">
                </el-option>
                <el-option
                  label="撤销"
                  value="revoke">
                </el-option>
              </el-select>
            </el-form-item>

            <!-- 绿博园对接的银行 -->
            <el-form-item
              label="银行POS选择（默认建行）"
              v-if="projectName==='lby'">
              <el-select
                v-model="form.posName"
                style="width:100%">
                <el-option
                  label="无"
                  value="">
                </el-option>
                <el-option
                  label="建行"
                  value="jianhang">
                </el-option>
                <el-option
                  label="农行"
                  value="nonghang">
                </el-option>
                <el-option
                  label="银联"
                  value="yinlian">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="其他配置" name="other">
          <el-form>
            <el-form-item label="身份证阅读器">
              <el-select
                v-model="form.idDevice"
                style="width:100%">
                <el-option
                  label="中控ID200"
                  value="zk">
                </el-option>
                <el-option
                  label="江苏社保卡密服"
                  value="tecsun">
                </el-option>
                <el-option
                  label="华视身份证读卡器"
                  value="hs">
                </el-option>
                <el-option
                  label="华视身份证读卡器（CVR-100N）"
                  value="hs-ws">
                </el-option>
                <el-option
                  label="精伦身份证读卡器"
                  value="jl">
                </el-option>
                <el-option
                  label="新中新F200"
                  value="xzx">
                </el-option>
                <el-option
                  label="东信EST-100"
                  value="donsee">
                </el-option>
                <el-option
                  label="东信EST-100R"
                  value="donsee-100R">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              v-if="form.idDevice==='tecsun'"
              label="身份证读卡器串口号">
              <el-input-number
                style="width:100%"
                v-model="form.idDevicePort"
                :controls="false"
                placeholder="在设备管理器里查看串口号（数字）"></el-input-number>
            </el-form-item>

            <el-form-item label="身份证阅读器web接口地址">
              <el-input
                v-model="form.idDeviceUrl"
                :placeholder="idDevicePlaceholder"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane v-if="showAdvance" label="高级设置（谨慎修改！！！）" name="advance">
          <el-form>
            <el-form-item label="软件名">
              <el-input v-model="form.appName"></el-input>
            </el-form-item>

            <el-form-item label="自定义logo">
              <el-button
                type="info"
                @click="selectFile('customLogo')">
                选择文件
              </el-button>
              <el-button
                type="danger"
                @click="handleDeleteLogo">
                清除自定义logo文件
              </el-button> <br>
              <img
                v-if="customLogoLoaded"
                :src="customLogoUrl"
                style="background:#ccc; padding:10px; height:50px; margin-top:10px">
            </el-form-item>

            <el-form-item label="模拟支付">
              <el-switch
                v-model="form.mock"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>

            <el-form-item label="模拟景区">
              <el-select v-model="form.scenicName">
                <el-option
                  label="景区"
                  value="">
                </el-option>
                <el-option
                  v-for="item in scenicOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="始终显示退订单按钮">
              <el-switch
                v-model="form.showRefundBtnAlways"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div
        class="btn-wrap">
        <div>
          <el-button
            type="danger"
            @click.native.prevent="clearLocalConfig">
            清空本地配置
          </el-button>
          <!-- <el-button @click="openConfig">
            打开配置文件
          </el-button> -->
          <el-button @click="openLog">
            打开日志文件目录
          </el-button>
        </div>

        <div>
          <el-button @click="handleBack">
            返回
          </el-button>

          <el-button
            type="primary"
            @click.native.prevent="handleSave">
            保存
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { isUrl, isEmpty } from '@/utils'
import { forEach } from 'lodash'

// const printer = require('printer')
const { ipcRenderer } = require('electron')
const ipc = require('electron').ipcRenderer
const fs = require('fs')

const scenicOptions = [
  '狼山景区',
  '西宁景区',
  '军山景区',
  '东方绿舟',
  '天津之眼',
  '伏羲山景区',
  '绿博园',
  '天水剧院'
]

// 印象妈祖客户端地址：http://36.250.162.193:81；印象妈祖升级地址：http://36.250.162.193:81/frontend

const userDataFolder = require('electron').remote.app.getPath('userData')
export default {
  computed: {
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    },
    idDevicePlaceholder () {
      let pc = ''
      switch (this.form.idDevice) {
        case 'hs':
          pc = '一般不用设置; 华视：http://127.0.0.1:19196'
          break
        case 'hs-ws':
          pc = '一般不用设置; 华视：ws://127.0.0.1:8800'
          break
        case 'xzx':
          pc = '一般不用设置; 新中新：http://localhost:8989'
          break
        default:
          pc = '一般不用设置'
      }

      return pc
    }
  },
  data () {
    const checkUrl = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入地址'))
      } else if (!isUrl(value)) {
        callback(new Error('输入的格式不正确'))
      } else {
        callback()
      }
    }

    // ‘印象妈祖’景区需要隐藏，设为true；其余景区为false
    // npm run start:mazu是为true; npm run start时为false
    // appName 印象妈祖票务系统

    return {
      activeTab: 'server',
      projectName: process.env.VUE_APP_PROJECT,
      scenicOptions,
      previewPath: '',
      currentDirectoryProp: '', // 当前要改变的目录路径属性
      currentFileProp: '', // 当前要改变文件路径属性
      tempUrl: '',
      customLogoUrl: '', // 添加上随机数，防止图片不更新
      customLogoLoaded: false,
      count: 0,
      showAdvance: false,
      firstTime: true,
      webviewIsReady: false,
      previewVisible: false,
      printWin: null,
      previewSize: {
        width: 0,
        height: 0
      },
      appName: process.env.VUE_APP_PROJECT_NAME,
      payChannelOptions: this.$localStore.get('payChannelOptions'),
      form: {
        faceApi: this.$localStore.get('faceApi') || 'faceApi',
        posName: this.$localStore.get('posName') || '',
        initNum: this.$localStore.get('initNum') || 1,
        ICCardLength: isEmpty(this.$localStore.get('ICCardLength')) ? '' : this.$localStore.get('ICCardLength'),
        defaultPayWay: this.$localStore.get('defaultPayWay') || '',
        idDevice: this.$localStore.get('idDevice') || 'zk',
        idDevicePort: this.$localStore.get('idDevicePort') || '',
        idDeviceUrl: this.$localStore.get('idDeviceUrl') || '',
        customLogo: require('path').join(userDataFolder, 'logo.png'),
        refundWay: this.$localStore.get('refundWay') || 'revoke',
        mock: this.$localStore.get('mock') || false,
        showRefundBtnAlways: this.$localStore.get('showRefundBtnAlways') || false,
        appName: this.$localStore.get('appName') || '',
        scenicName: this.$localStore.get('scenicName') || '',
        softposPath: this.$localStore.get('softposPath') || 'C:\\gmc',
        serverUrl: this.$localStore.get('serverUrl') || '',
        updateUrl: this.$localStore.get('updateUrl') || '',
        /* 妈祖需要去掉默认的升级地址 updateUrl: this.$localStore.get('updateUrl'), 这里不可用data返回里的布尔值，而应用上面的变量 */
        defaultPrinter: this.$localStore.get('defaultPrinter') || '',
        defaultSmallTicketPrinter: this.$localStore.get('defaultSmallTicketPrinter') || '',
        quickSupport: this.$localStore.get('quickSupport') || false,
        encryption: this.$localStore.get('encryption') || false,
        encryption_aes: this.$localStore.get('encryption_aes') || false,
        autoPrint: this.$localStore.get('autoPrint') || false,
        termId: this.$localStore.get('termId') || '',
        showScenicTag: this.$localStore.get('showScenicTag') || false,
        faceModel: this.$localStore.get('faceModel') || 'ssdMobilenetv1'
      },
      defaultPrinter: '',
      rules: {
        serverUrl: [{ validator: checkUrl, trigger: 'blur', required: true }],
        updateUrl: [{ validator: checkUrl, trigger: 'blur', required: true }]
      },
      printers: []
    }
  },
  methods: {
    init () {
      this.getPrinters()

      // 图片路径存在则显示
      this.isExist(this.form.customLogo).then(() => {
        this.customLogoLoaded = true
        this.customLogoUrl = 'file://' + this.form.customLogo + '?v=' + Math.random()
      })

      ipc.on('selected-directory', this.handleSelectDirectory)

      ipc.on('selected-file', this.handleSelectFile)
    },
    customMazuSetupProductUrl () {
      // 妈祖景区要求写死生产地址。印象妈祖客户端地址：http://36.250.162.193:81；印象妈祖升级地址：http://36.250.162.193:81/frontend
      if (this.appName.indexOf('妈祖') > 0) {
        this.form.serverUrl = this.form.serverUrl || 'http://36.250.162.193:81'
        this.form.updateUrl = this.form.updateUrl || 'http://36.250.162.193:81/frontend'
      }
    },
    handleDeleteLogo () {
      this.customLogoLoaded = false
      this.customLogoUrl = ''
    },
    handleHideClick () {
      this.count++
      if (this.count === 6) {
        this.showAdvance = true
      }
    },
    clearLocalConfig () {
      console.log('清空')
      this.$confirm('确定清空吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$localStore.clear()
        this.$message.success('已清空配置，请等待刷新')
        setTimeout(() => {
          window.location.reload()
        }, 2000)
      })
    },
    async handleSave () {
      const { serverUrl } = this.form
      if (!serverUrl) {
        this.$message.error('请输入服务器地址')
        return
      }

      if (!isUrl(serverUrl)) {
        this.$message.error('输入的格式不正确')
        return
      }

      // 复制更新logo文件
      if (this.tempUrl) {
        await this.copyFile(this.form.customLogo, this.tempUrl)
      }

      if (!this.customLogoUrl) {
        await this.deleteFile(this.form.customLogo)
      }

      forEach(this.form, (value, key) => {
        this.$localStore.set(key, value)
      })
      // this.$localStore.set(this.form)
      this.$message.success('配置完成，请等待刷新')

      setTimeout(() => {
        window.location.reload()
        this.$router.push('/')
      }, 2000)
    },
    handleBack () {
      if (!this.$localStore.get('serverUrl')) {
        this.$message.error('请完成地址配置。')
      }
      window.location.reload()
      this.$router.push('/')
    },
    handlePreview () {
      this.previewVisible = true
    },
    getPrinters () {
      ipcRenderer.send('getPrinters')
      ipcRenderer.on('sendPrinters', (event, printers) => {
        this.printers = printers

        printers.length > 0 && (this.defaultPrinter = printers.find(i => i.isDefault).name)
        this.form.defaultPrinter = this.$localStore.get('defaultPrinter') || this.defaultPrinter
      })
    },
    openConfig () {
      this.$localStore.openInEditor()
    },
    openLog () {
      const log = require('electron-log')
      require('electron').shell.showItemInFolder(log.transports.file.findLogPath())
    },
    selectFolder (prop) {
      this.currentDirectoryProp = prop
      ipc.send('open-directory-dialog')
    },
    selectFile (prop) {
      this.currentFileProp = prop
      ipc.send('open-file-dialog')
    },
    openFolder () {
      require('electron').shell.showItemInFolder(this.form.softposPath)
    },
    copyFile (filename, src) {
      return new Promise((resolve, reject) => {
        this.isExist(src).then(() => {
          copy(filename, src)
        })

        function copy (filename, src) {
          const readStream = fs.createReadStream(src) // filename如果不存在，则会在路径上新建文件
          const writeStream = fs.createWriteStream(filename)

          writeStream.on('finish', handleEnd)

          readStream.pipe(writeStream)

          function handleEnd (data) {
            resolve()
            writeStream.removeListener('finish', handleEnd)
          }
        }
      })
    },
    deleteFile (src) {
      return new Promise((resolve, reject) => {
        fs.unlink(src, function (error) {
          if (error) {
            console.log(error)
          }
          resolve()
        })
      })
    },
    isExist (src) {
      return new Promise((resolve, reject) => {
        fs.stat(src, (err, stats) => {
          if (err) {
            reject(err)
            console.log(err)
          }
          resolve()
        })
      })
    },
    handleSelectDirectory (event, path) {
      this.form[this.currentDirectoryProp] = path[0]
    },
    handleSelectFile (event, path) {
      this[this.currentFileProp] = path[0]
      this.customLogoLoaded = true
      let fileType = path[0].split('.').pop()
      if (['png', 'jpg', 'gif'].indexOf(fileType.toLowerCase()) < 0) {
        this.$message.error('无效的文件类型，请选择图片')
        return
      }
      // 显示选择的图片
      this.customLogoUrl = 'file://' + path[0] + '?v=' + Math.random()
      this.tempUrl = path[0]
    }
  },
  created () {
    this.init()
  },
  beforeDestroy () {
    ipc.removeListener('selected-directory', this.handleSelectDirectory)

    ipc.removeListener('selected-file', this.handleSelectFile)
  }
}
</script>

<style lang="scss" scoped>
.configPage {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #fff;

  h1 {
    font-size: 24px;
    font-weight: bold;
    line-height: 100px;
    color: #333;
    text-align: center;
  }

  ::v-deep .el-form-item__label {
    float: none;
  }

  h3 {
    color: $blue;
    border-bottom: 1px solid #ddd;
    line-height: 2;
    margin-bottom: 10px;
    font-weight: bold;
  }
}

.bg {
  position: absolute;
  top: 100px;
  left: 50%;
  width: 200%;
  padding-top: 100%;
  background: #F8F9FD;
  border-radius: 50%;
  transform: translate(-50%, 0);
}

.content {
  position: absolute;
  margin: 100px 20px 20px 20px;
  width: calc(100% - 40px);
  height: calc(100% - 120px);
  overflow: auto;
  background: #fff;
  box-shadow: 6px 0px 28px 0px #C4CBD6;
  border-radius: 12px;
  left: 0;
  top: 0;

  .el-tabs {
    margin: 0 20px;
    width: calc(100% - 40px);
    height: calc(100% - 50px);

    &__content {
      height: 100%;
    }
  }
}

.btn-wrap {
  display: flex;
  justify-content: space-around;
  margin-bottom: 10px;
}

.preview-wrap {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.5);
  overflow: auto;

  .inner {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
    padding: 50px 30px 30px;
    border-radius: 10px;
  }

  .close {
    position: absolute;
    right: 16px;
    top: 16px;
    cursor: pointer;
    font-size: 20px;
  }

  .ticket {
    box-shadow: 2px 2px 20px #ddd;
    padding: 10px;
    overflow: hidden;
  }

  .btn-wrap {
    margin-top: 30px;
    text-align: center;
  }

  .rotate {
    transform: translateY(-100%) rotate(90deg);
    transform-origin: 0 100%;
  }
}
</style>
