<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="代理商名称" prop="agentName">
        <el-input
          v-model="queryParams.agentName"
          placeholder="请输入代理商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="AppID" prop="appId">
        <el-input
          v-model="queryParams.appId"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="['ct:agentAccount:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ct:agentAccount:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ct:agentAccount:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ct:agentAccount:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="agentAccountList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form style="margin: 0 80px;" label-width="120px">
            <el-form-item label="IP白名单">
              {{props.row.ipList}}
            </el-form-item>
            <el-form-item label="商品">
              <el-tag type="success"
                v-for="goods in props.row.agentAccountGoodVoList"
                :key="goods.id"
                style="margin-right: 10px"
                >{{goods.title}}</el-tag>
            </el-form-item>
            <el-form-item label="备注">
              {{props.row.remark}}
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="代理商名称" fixed align="center" prop="agentName" />
      <el-table-column label="别名" width="100" align="center" prop="personnelId" />
      <el-table-column label="APP ID" width="290" align="center" prop="appId" />
      <el-table-column label="APP Secret" width="290" align="center" prop="appSecret" />
      <el-table-column label="公钥" width="80" align="center" prop="appSecret">
        <template slot-scope="scope">
          <el-button @click="viewKey(scope.row, 'agentPublicKey')" size="mini" type="primary">复制</el-button>
        </template>
      </el-table-column>
      <el-table-column label="私钥" width="80" align="center" prop="appSecret">
        <template slot-scope="scope">
          <el-button @click="viewKey(scope.row, 'platformPrivateKey')" size="mini" type="primary">复制</el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.agent_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" width="100" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ct:agentAccount:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ct:agentAccount: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="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="代理商" prop="agentId">
              <el-select
                v-model="form.agentId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="getAgentList"
                :loading="loading"
                :readonly="form.id!=null"
                @change="selectAgent"
                style="width: 100%;">
                <el-option
                  v-for="item in agentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="别名" prop="personnelId">
              <el-input v-model="form.personnelId" placeholder="请输入别名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="验证URL" prop="verifyUrl">
              <el-input v-model="form.verifyUrl" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="电信商品" prop="goodsIds">
              <el-select
                v-model="form.goodsIds"
                filterable
                multiple
                :loading="loading"
                style="width: 100%;">
                <el-option
                  v-for="item in goodsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="状态" prop="status" v-if="form.id!==undefined">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.good_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="IP白名单(英文逗号分割)" prop="ipList">
              <el-input v-model="form.ipList" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAgentAccount, getAgentAccount, delAgentAccount, addAgentAccount, updateAgentAccount } from "@/api/ct/agentAccount";
import { listAgent } from "@/api/ct/agent";
import { listGood } from "@/api/ct/good";

export default {
  name: "AgentAccount",
  dicts: ['agent_status', 'good_status'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理商账号表格数据
      agentAccountList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        agentId: undefined,
        agentName: undefined,
        personnelId: undefined,
        appId: undefined,
        appSecret: undefined,
        ipList: undefined,
        verifyUrl: undefined,
        platformPublicKey: undefined,
        platformPrivateKey: undefined,
        agentPublicKey: undefined,
        agentPrivateKey: undefined,
        status: undefined,
        goodsIds: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        agentId: [
          { required: true, message: "不能为空", trigger: "change" }
        ],
        personnelId: [
          { required: true, message: "不能为空", trigger: "change" }
        ],
        ipList: [
          { required: true, message: "不能为空", trigger: "change" }
        ],
        goodsIds: [
          { required: true, message: "不能为空", trigger: "change" }
        ]
      },
      agentList: [],
      goodsList: [],
    };
  },
  created() {
    this.getList()
    this.getAgentList()
    this.getGoodsList()
  },
  methods: {
    viewKey(row, key) {
      var tempElement = document.createElement("textarea");
      tempElement.value = row[key];
      document.body.appendChild(tempElement);
      tempElement.select();
      document.execCommand("copy");
      // 移除临时元素
      document.body.removeChild(tempElement);
      this.$message({
        message: '已复制到剪切板',
        type: 'success'
      });
    },
    getAgentList(query) {
      this.loading = true;
      listAgent({pageNum: 1, pageSize: 20, name: query, status: 1}).then(res=>{
        this.agentList = res.rows
        this.loading = false;
      })
    },
    selectAgent(id) {
      this.agentList.forEach(agent=>{
        if (id == agent.id) {
          this.form.agentName = agent.name
        }
      })
    },
    getGoodsList() {
      listGood({pageNum: 1, pageSize: 10000000, status: 1}).then(res=>{
        this.goodsList = res.rows
      })
    },
    /** 查询代理商账号列表 */
    getList() {
      this.loading = true;
      listAgentAccount(this.queryParams).then(response => {
        this.agentAccountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        agentId: undefined,
        agentName: undefined,
        personnelId: undefined,
        appId: undefined,
        appSecret: undefined,
        ipList: undefined,
        verifyUrl: undefined,
        platformPublicKey: undefined,
        platformPrivateKey: undefined,
        agentPublicKey: undefined,
        agentPrivateKey: undefined,
        status: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        goodsIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加代理商账号";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getAgentAccount(id).then(response => {
        this.loading = false;
        this.form = {goodsIds:[], ...response.data};
        let tmp = []
        response.data.agentAccountGoodVoList.forEach(item=>{
          tmp.push(item.goodId)
        })
        this.form.goodsIds = tmp
        this.open = true;
        this.title = "修改代理商账号";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateAgentAccount(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addAgentAccount(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除代理商账号编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delAgentAccount(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ct/agentAccount/export', {
        ...this.queryParams
      }, `agentAccount_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
