<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="appid" prop="appid">
        <el-input
          v-model="queryParams.appid"
          placeholder="请输入appid"
          clearable
          size="small"
          @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="['course:playSourceConfig: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="['course:playSourceConfig: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="['course:playSourceConfig:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 绑定商户弹窗 -->
    <el-dialog title="绑定商户" :visible.sync="bindDialog.open" width="500px" append-to-body>
      <el-form ref="bindForm" :model="bindDialog.form" label-width="100px">
        <el-form-item label="商户类型" prop="merchantType">
          <el-select
            v-model="bindDialog.form.merchantType"
            placeholder="请选择商户类型"
            clearable
            size="small"
            style="width: 100%"
            @change="handleMerchantTypeChange"
          >
            <el-option
              v-for="dict in merchantTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商户号" prop="merchantId">
          <el-select
            v-model="bindDialog.form.merchantId"
            placeholder="请选择商户号"
            clearable
            size="small"
            style="width: 100%"
            :disabled="!bindDialog.form.merchantType"
          >
            <el-option
              v-for="item in merchantOptions"
              :key="item.id"
              :label="item.merchantId"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBind">确 定</el-button>
        <el-button @click="bindDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="图标" align="center" prop="img">
        <template slot-scope="scope">
          <el-image
            style="width: 80px; height: 80px"
            :src="scope.row.img"
            :preview-src-list="[scope.row.img]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="原始ID" align="center" prop="originalId" />
      <el-table-column label="appId" align="center" prop="appid" />
      <el-table-column label="secret" align="center" prop="secret" />
      <el-table-column label="token" align="center" prop="token" />
      <el-table-column label="aesKey" align="center" prop="aesKey" />
      <el-table-column label="msgDataFormat" align="center" prop="msgDataFormat" />
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag  :options="typesOptions" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="修改时间" align="center" prop="updateTime" />
      <el-table-column label="商户号" align="center" prop="merchantNo">
        <template slot-scope="scope">
          <span>{{ scope.row.merchantNo || '未绑定' }}</span>
        </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="['course:playSourceConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:playSourceConfig:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleBind(scope.row)"
          >绑定</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="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="图标" prop="img">
          <ImageUpload v-model="form.img" :limit="1" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择类型">
            <el-option
              v-for="item in typesOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="原始id" prop="originalId">
          <el-input v-model="form.originalId" placeholder="请输入原始id" />
        </el-form-item>
        <el-form-item label="appid" prop="appid">
          <el-input v-model="form.appid" placeholder="请输入appid" />
        </el-form-item>
        <el-form-item label="secret" prop="secret">
          <el-input v-model="form.secret" placeholder="请输入secret" />
        </el-form-item>
        <el-form-item label="token" prop="token">
          <el-input v-model="form.token" placeholder="请输入token" />
        </el-form-item>
        <el-form-item label="aesKey" prop="aesKey">
          <el-input v-model="form.aesKey" placeholder="请输入aesKey" />
        </el-form-item>
        <el-form-item label="msgDataFormat" prop="msgDataFormat">
          <el-input v-model="form.msgDataFormat" placeholder="请输入msgDataFormat" />
        </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 {list, get, update, add, del, bindMerchant} from '@/api/course/coursePlaySourceConfig'
import {listMerchantAppConfig} from '@/api/merchantAppConfig/merchantAppConfig'

export default {
  name: 'CoursePlaySourceConfig',
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        appid: null
      },
      showSearch: true,
      single: true,
      multiple: true,
      ids: [],
      loading: false,
      list: [],
      total: 0,
      typesOptions: [],
      merchantTypeOptions: [],
      merchantOptions: [],
      bindDialog: {
        open: false,
        currentAppId: null,
        form: {
          merchantType: null,
          merchantId: null
        }
      },
      title: null,
      open: false,
      form: {},
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        appid: [
          { required: true, message: "appid不能为空", trigger: "blur" }
        ],
        img: [
          { required: true, message: "图标不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "blur" }
        ],
        originalId: [
          { required: true, message: "原始id不能为空", trigger: "blur" }
        ],
        secret: [
          { required: true, message: "secret不能为空", trigger: "blur" }
        ],
        token: [
          { required: true, message: "token不能为空", trigger: "blur" }
        ],
        aesKey: [
          { required: true, message: "aesKey不能为空", trigger: "blur" }
        ],
        msgDataFormat: [
          { required: true, message: "msgDataFormat不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getDicts("play_source_type").then(response => {
      this.typesOptions = response.data.map(item =>  {
        return {
        ...item,
        listClass: 'primary'}
      })
    });
    this.getDicts("sys_pay_mode").then(response => {
      this.merchantTypeOptions = response.data;
    });
    this.getList();
  },
  methods: {


    // 打开绑定弹窗
    handleBind(row) {
      this.bindDialog.currentAppId = row.appid;
      this.bindDialog.form.merchantType = null;
      this.bindDialog.form.merchantId = null;
      this.merchantOptions = [];
      this.bindDialog.open = true;
    },
    // 商户类型变更时查询商户
    handleMerchantTypeChange(val) {
      if (!val) {
        this.merchantOptions = [];
        this.bindDialog.form.merchantId = null;
        return;
      }
      listMerchantAppConfig({
        merchantType: val,
        appIds: this.bindDialog.currentAppId,
        isDeleted: '0'
      }).then(res => {
        this.merchantOptions = res.rows || [];
        this.bindDialog.form.merchantId = null;
      }).catch(() => {
        this.merchantOptions = [];
      });
    },
    // 确认绑定
    submitBind() {
      if (!this.bindDialog.form.merchantId) {
        this.$message.warning("请选择商户号");
        return;
      }
      bindMerchant({
        appId: this.bindDialog.currentAppId,
        merchantConfigId: this.bindDialog.form.merchantId
      }).then(res => {
        this.msgSuccess("绑定成功");
        this.bindDialog.open = false;
        this.getList();
      }).catch(() => {});
    },


    getList() {
      this.loading = true;
      list(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.getList();
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加点播配置"
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      get(id).then(response => {
        this.form = {
          ...response.data,
          type: response.data.type.toString()
        }
        this.open = true
        this.title = "修改点播配置"
      })
    },
    handleDelete(row) {
      const id = row.id || this.ids
      this.$confirm('是否确认删除点播配置编号为"' + id + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return del(id);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            update(this.form).then(response => {
              const {code, msg} = response
              if (code !== 200) {
                this.msgError(msg)
                return
              }
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            add(this.form).then(response => {
              const {code, msg} = response
              if (code !== 200) {
                this.msgError(msg)
                return
              }
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        name: null,
        appid: null,
        secret: null,
        img: null,
        originalId: null,
        token: 'cbnd7lJvkripVOpyTFAna6NAWCxCrvC',
        aesKey: 'HlEiBB55eaWUaeBVAQO3cWKWPYv1vOVQSq7nFNICw4E',
        msgDataFormat: 'JSON',
        type: '1'
      }
      this.resetForm("form");
    }
  },
}
</script>

<style scoped>

</style>
