<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="agentId">
        <el-select v-model="queryParams.agentAccountId" filterable clearable>
          <el-option
            v-for="item in agentAccountList" :key="item.value"
            :label="item.agentName+'('+item.personnelId+')'"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品" prop="saleId">
        <el-select v-model="queryParams.saleId" clearable>
          <el-option
            v-for="item in goodsList" :key="item.id"
            :label="item.name"
            :value="item.saleId"></el-option>
        </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="['ct:agentAccountGood: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:agentAccountGood: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:agentAccountGood: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:agentAccountGood:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="agentAccountGoodList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="true"/>
      <el-table-column label="代理商" align="center" prop="agentId">
        <template slot-scope="scope">
          <span>{{getAgentName(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="电信ID" align="center" prop="personnelId" />
      <el-table-column label="商品" align="center" prop="goodId">
        <template slot-scope="scope">
          <span>{{getGoodName(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品ID" align="center" prop="saleId" />
      <el-table-column label="是否需要验证" align="center" prop="isNeedVerify">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isNeedVerify==1" type="success">Y</el-tag>
          <el-tag v-else type="danger">N</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="限制下单数量" align="center" prop="registerCount" />
      <el-table-column label="完成开卡数量" align="center" prop="completeCount" />
      <el-table-column label="办理中数量" align="center" prop="waitCount" />
      <el-table-column label="名单人员上限数" align="center" prop="verifyCount" />
      <el-table-column label="验证完成数量" align="center" prop="verifiedCount" />
      <el-table-column label="临时密码" align="center" prop="tmpPassword" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="商品图片" align="center" prop="images" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" 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="['ct:agentAccountGood:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ct:agentAccountGood:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="copyUrl(scope.row, 0)"
          >办理地址</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="copyUrl(scope.row, 1)"
          >管理地址</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="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="代理商" prop="agentAccountId">
          <el-select v-model="form.agentAccountId" filterable placeholder="请选择代理商"
            @change="selectAgentAccount"
            :disabled="form.id != undefined">
            <el-option
              v-for="item in agentAccountList" :key="item.value"
              :label="item.agentName+'('+item.personnelId+')'"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电信商品" prop="goodId">
          <el-select v-model="form.goodId" filterable placeholder="请选择电信商品"
            @change="selectGood"
            :disabled="form.id != undefined">
            <el-option
              v-for="item in goodsList" :key="item.value"
              :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="是否需要验证" prop="isNeedVerify">
          <el-radio-group v-model="form.isNeedVerify">
            <el-radio-button :label="1">是</el-radio-button>
            <el-radio-button :label="0">否</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="限制下单数量" prop="registerCount">
          <el-input-number v-model="form.registerCount" :min="0" placeholder="请输入限制下单数量" />
        </el-form-item>
        <el-form-item label="名单人员上限数" prop="verifyCount">
          <el-input-number v-model="form.verifyCount" :min="0" placeholder="请输入名单人员上限数" />
        </el-form-item>
        <el-form-item label="临时密码" prop="tmpPassword">
          <el-input v-model="form.tmpPassword" placeholder="请输入临时密码" />
        </el-form-item>
        <el-form-item label="商品图片" prop="imageIds">
          <image-upload :limit="20" :fileSize="10" v-model="form.imageIds"/>
        </el-form-item>
      </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 Base64 from '@/utils/base64.js';
import { listAgentAccountGood, getAgentAccountGood, delAgentAccountGood, addAgentAccountGood, updateAgentAccountGood } from "@/api/ct/agentAccountGood";
import { listAgent } from "@/api/ct/agent";
import { listAgentAccount } from "@/api/ct/agentAccount";
import { listGood } from "@/api/ct/good";
import { listByIds } from "@/api/system/oss";

export default {
  name: "AgentAccountGood",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理商商品表格数据
      agentAccountGoodList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        agentId: undefined,
        agentAccountId: undefined,
        personnelId: undefined,
        goodId: undefined,
        saleId: undefined,
        isNeedVerify: undefined,
        registerCount: undefined,
        verifyCount: undefined,
        tmpPassword: undefined,
        images: undefined,
        imageIds: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        isNeedVerify: [
          { required: true, message: "是否需要验证不能为空", trigger: "blur" }
        ],
        agentAccountId: [
          { required: true, message: "代理商不能为空", trigger: "blur" }
        ],
        goodId: [
          { required: true, message: "电信商品不能为空", trigger: "blur" }
        ],
      },
      agentList: [],
      agentAccountList: [],
      goodsList: [],
    };
  },
  created() {
    this.getAgentList();
    this.getAgentAccountList();
    this.getGoodsList();
    this.getList();
  },
  methods: {
    selectAgentAccount(val) {
      this.agentAccountList.forEach(item=>{
        if (item.id == val) {
          this.form.agentId = item.agentId
        }
      })
    },
    selectGood(val) {
      this.goodsList.forEach(item=>{
        if (item.id == val) {
          this.form.saleId = item.saleId
          this.form.personnelId = item.personnelId
        }
      })
    },
    getAgentName(row) {
      let name = ''
      this.agentAccountList.forEach(item=>{
        if (row.agentAccountId == item.id) {
          name = item.agentName+'('+item.personnelId+')'
        }
      })
      return name
    },
    getGoodName(row) {
      let name = ''
      this.goodsList.forEach(item=>{
        if (row.goodId == item.id) {
          name = item.name
        }
      })
      return name
    },
    getAgentList() {
      this.loading = true;
      listAgent({pageNum: 1, pageSize: 10000000, status: 1}).then(res=>{
        this.agentList = res.rows
        this.loading = false;
      })
    },
    getAgentAccountList() {
      this.loading = true;
      listAgentAccount({pageNum: 1, pageSize: 10000000, status: 1}).then(response => {
        this.agentAccountList = response.rows;
        this.loading = false;
      });
    },
    getGoodsList() {
      listGood({pageNum: 1, pageSize: 10000000, status: 1}).then(res=>{
        this.goodsList = res.rows
      })
    },
    /** 查询代理商商品列表 */
    getList() {
      this.loading = true;
      listAgentAccountGood(this.queryParams).then(response => {
        this.agentAccountGoodList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        agentId: undefined,
        agentAccountId: undefined,
        personnelId: undefined,
        goodId: undefined,
        saleId: undefined,
        isNeedVerify: 0,
        registerCount: 0,
        verifyCount: 0,
        tmpPassword: undefined,
        images: undefined,
        imageIds: undefined,
        delFlag: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        remark: undefined
      };
      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
      getAgentAccountGood(id).then(response => {
        this.loading = false;
        this.form = response.data;
        // this.form.isNeedVerify = this.form.isNeedVerify.split(",");
        this.open = true;
        this.title = "修改代理商商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.imageIds) {
            listByIds(this.form.imageIds).then(res=>{
              let tmp = []
              res.data.forEach(o=>{
                tmp.push(o.url)
              })
              this.form.images = tmp.join(",")
              this.save()
            })
          } else {
            this.save()
          }
        }
      });
    },
    save() {

      if (this.form.id != null) {
        updateAgentAccountGood(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        }).finally(() => {
          this.buttonLoading = false;
        });
      } else {
        addAgentAccountGood(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 delAgentAccountGood(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ct/agentAccountGood/export', {
        ...this.queryParams
      }, `agentAccountGood_${new Date().getTime()}.xlsx`)
    },
    copyUrl(row, type) {
      let base64 = new Base64()
      var tempElement = document.createElement("textarea");
      let code = base64.encode(row.id+','+row.agentAccountId+','+row.goodId)
      let url = 'https://ct-platform-h5.oinary.com/#/?code='+code
      if (type == 1) {
        url = 'https://ct-platform-h5-admin.oinary.com/#/?code='+code
      }
      tempElement.value = url;
      document.body.appendChild(tempElement);
      tempElement.select();
      document.execCommand("copy");
      // 移除临时元素
      document.body.removeChild(tempElement);
      this.$message({
        message: '已复制到剪切板',
        type: 'success'
      });
    }
  }
};
</script>
