<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="AppKey" prop="appKey">
        <el-input v-model="queryParams.appKey" placeholder="AppKey" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 120px">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['jarvis:erpOpenConfig:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="list">
      <el-table-column label="ID" prop="id" width="70" />
      <el-table-column label="AppKey" prop="appKey" min-width="140" show-overflow-tooltip />
      <el-table-column label="闲鱼会员名" prop="xyUserName" width="120" show-overflow-tooltip />
      <el-table-column label="快递编码" prop="expressCode" width="100" show-overflow-tooltip />
      <el-table-column label="快递名称" prop="expressName" width="100" show-overflow-tooltip />
      <el-table-column label="状态" prop="status" width="72">
        <template slot-scope="scope">
          <span>{{ scope.row.status === '0' ? '正常' : '停用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="orderNum" width="70" />
      <el-table-column label="备注" prop="remark" min-width="120" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['jarvis:erpOpenConfig:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['jarvis:erpOpenConfig:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-dialog title="闲管家快递公司（点击行填入表单）" :visible.sync="expressOpen" width="720px" append-to-body @open="loadExpressList">
      <p style="margin:0 0 8px;font-size:12px;color:#909399">签名与 POST 体必须为 <code>{}</code>；Apifox 里 body 留空会导致签名校验失败。</p>
      <el-table v-loading="expressLoading" :data="expressList" size="small" max-height="400" @row-click="pickExpress">
        <el-table-column prop="code" label="编码(code)" width="140" />
        <el-table-column prop="express_name" label="名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="express_alias" label="简称" width="100" />
        <el-table-column prop="is_hot" label="热门" width="72">
          <template slot-scope="scope">{{ scope.row.is_hot ? '是' : '' }}</template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="open" width="560px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="AppKey" prop="appKey">
          <el-input v-model="form.appKey" placeholder="开放平台 AppKey" :disabled="!!form.id" />
        </el-form-item>
        <el-form-item label="AppSecret" prop="appSecret">
          <el-input v-model="form.appSecret" type="password" show-password placeholder="AppSecret" />
        </el-form-item>
        <el-form-item label="闲鱼会员名" prop="xyUserName">
          <el-input v-model="form.xyUserName" placeholder="展示用，可选" />
        </el-form-item>
        <el-form-item label="快递编码" prop="expressCode">
          <el-input v-model="form.expressCode" placeholder="如日日顺为 rrs（以平台列表为准）">
            <el-button slot="append" type="primary" @click="openExpressDialog">拉取列表</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="快递名称" prop="expressName">
          <el-input v-model="form.expressName" placeholder="如 日日顺" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" controls-position="right" style="width: 160px" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listErpOpenConfig, getErpOpenConfig, addErpOpenConfig, updateErpOpenConfig, delErpOpenConfig, listGoofishExpressCompanies } from '@/api/jarvis/goofish'

export default {
  name: 'ErpOpenConfig',
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      list: [],
      open: false,
      title: '',
      queryParams: { pageNum: 1, pageSize: 10, appKey: undefined, status: undefined },
      form: {},
      expressOpen: false,
      expressLoading: false,
      expressList: [],
      rules: {
        appKey: [{ required: true, message: 'AppKey 不能为空', trigger: 'blur' }],
        appSecret: [{ required: true, message: 'AppSecret 不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态必选', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listErpOpenConfig(this.queryParams).then(res => {
        this.list = res.rows
        this.total = res.total
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    reset() {
      this.form = {
        id: undefined,
        appKey: undefined,
        appSecret: undefined,
        xyUserName: undefined,
        expressCode: undefined,
        expressName: '日日顺',
        status: '0',
        orderNum: 0,
        remark: undefined
      }
      this.resetForm('form')
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增应用配置'
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id
      getErpOpenConfig(id).then(res => {
        this.form = res.data
        this.open = true
        this.title = '修改应用配置'
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        if (this.form.id != null) {
          updateErpOpenConfig(this.form).then(() => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
        } else {
          addErpOpenConfig(this.form).then(() => {
            this.$modal.msgSuccess('新增成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
    },
    openExpressDialog() {
      this.expressOpen = true
    },
    loadExpressList() {
      const appKey = this.form && this.form.appKey ? this.form.appKey : undefined
      this.expressLoading = true
      listGoofishExpressCompanies(appKey).then(res => {
        const data = res.data || {}
        this.expressList = data.list || []
        this.expressLoading = false
        if (!this.expressList.length) {
          this.$modal.msgWarning('列表为空或未返回 list，请检查后台报错或密钥')
        }
      }).catch(() => { this.expressLoading = false })
    },
    pickExpress(row) {
      if (!row) return
      this.form.expressCode = row.code
      this.form.expressName = row.express_name || row.express_alias || ''
      this.expressOpen = false
      this.$modal.msgSuccess('已填入：' + row.code)
    },
    handleDelete(row) {
      this.$modal.confirm('是否确认删除编号为 ' + row.id + ' 的配置？').then(() => {
        return delErpOpenConfig(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    }
  }
}
</script>
