<template>
  <container>
    <!--    <div-->
    <!--      slot="right"-->
    <!--      style="margin-bottom: 10px"-->
    <!--    >-->
    <!--            <el-button-->
    <!--              size="mini"-->
    <!--              type="primary"-->
    <!--              @click="openModel(false)"-->
    <!--            >-->
    <!--              新增-->
    <!--            </el-button>-->
    <!--    </div>-->
    <el-table :data="pay_list">
      <el-table-column prop="id" label="ID" width="70"></el-table-column>
      <el-table-column prop="title" label="支付方式"></el-table-column>
      <el-table-column prop="defaultStatus" label="是否默认">
        <template slot-scope="scope">
          <span v-if="scope.row.defaultStatus === 5" class="success-status">
            是
          </span>
          <span v-else class="info-status">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="enableStatus" label="状态">
        <template slot-scope="scope">
          <el-switch
            v-if="$accessCheck($Access.PayListUpdateEnableStatus)"
            v-model="scope.row.enableStatus"
            class="switchStyle"
            active-color="#36B365"
            :active-value="5"
            :inactive-value="4"
            active-text="启用"
            inactive-text="禁用"
            @change="statusSet($event, scope.row)"
          ></el-switch>
          <div v-else>
            <span v-if="scope.row.enableStatus === 5" class="success-status">
              启用
            </span>
            <span v-else class="danger-status">禁用</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template slot-scope="scope">
          <el-button-group class="table-btn-group">
            <!--            :disabled="scope.row.id === 3"-->
            <el-button
              v-if="$accessCheck($Access.PayListEditPayment)"
              type="text"
              @click="openModel(true, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="$accessCheck($Access.PayListUpdateDefaultStatus)"
              :disabled="scope.row.defaultStatus === 5"
              type="text"
              @click="defaultData(scope.row.id)"
            >
              设为默认
            </el-button>
          </el-button-group>
          <!--          <el-tooltip-->
          <!--            content="删除"-->
          <!--            placement="top"-->
          <!--          >-->
          <!--            <el-button-->
          <!--              @click="delData(scope.row.id)"-->
          <!--              size="mini"-->
          <!--              type="danger"-->
          <!--              icon="el-icon-delete"-->
          <!--            ></el-button>-->
          <!--          </el-tooltip>-->
        </template>
      </el-table-column>
    </el-table>
    <FooterPage
      :page-size="pageSize"
      :total-page.sync="total"
      :current-page.sync="page"
      @pageChange="pageChange"
      @sizeChange="sizeChange"
    ></FooterPage>
    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :title="(is_edit ? '编辑' : '新增') + '支付方式'"
      :visible.sync="show_model"
      width="40%"
      style="font-size: 10px"
    >
      <el-form
        ref="add_form"
        :model="add_form"
        size="small"
        :rules="rules"
        label-width="200px"
      >
        <el-form-item label="支付名称:" prop="title">
          <el-input
            v-model="add_form.title"
            :disabled="true"
            placeholder="请输入支付名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否默认:" prop="defaultStatus">
          <el-switch
            v-model="add_form.defaultStatus"
            :active-value="5"
            :inactive-value="4"
          ></el-switch>
        </el-form-item>
        <el-form-item label="排序:" prop="sorts">
          <el-input-number
            v-model="add_form.paymentData.sorts"
            :controls="false"
            placeholder="设置排序"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否禁用:" prop="enableStatus">
          <el-radio-group v-model="add_form.enableStatus">
            <el-radio :label="4">是</el-radio>
            <el-radio :label="5">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支付类型:" prop="payType">
          <el-input
            v-model="add_form.paymentData.payType"
            disabled
            placeholder="支付类型"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="paymentName === '银行打款'" label="财务帐户:">
          <el-input
            v-model="add_form.paymentData.financeAccountName"
            readonly
            size="small"
            placeholder="结算账户"
            style="width: 200px"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="account_show = true"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item v-if="paymentName === '银行打款'" label="启用条件:">
          <span style="margin-right: 10px">满</span>
          <el-input-number
            v-model="add_form.paymentData.limit"
            :controls="false"
            placeholder="打款限额"
          ></el-input-number>
          <span style="padding-left: 10px">元启用</span>
          <p class="form-tip">
            订单金额大于{{
              add_form.paymentData.limit || "未设置"
            }}元，启用银行打款
          </p>
        </el-form-item>
        <el-form-item
          v-if="['微信支付', '支付宝支付', '余额支付'].includes(paymentName)"
          label="期初余额:"
          prop="beginMoney"
        >
          <el-input-number
            v-model="add_form.paymentData.beginMoney"
            :controls="false"
            :disabled="!!appid"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          v-if="paymentName === '微信支付'"
          label="微信小程序appId:"
          prop="appid"
        >
          <el-input
            v-model="add_form.paymentData.appid"
            placeholder="请输入微信小程序appId"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="['微信支付', '支付宝支付'].includes(paymentName)"
          label="移动应用appId:"
          prop="mobileAppid"
        >
          <el-input
            v-model="add_form.paymentData.mobileAppid"
            placeholder="请输入移动应用appId"
          ></el-input>
        </el-form-item>
        <div v-if="paymentName === '微信支付'">
          <el-form-item label="商户类型:">
            <el-select v-model="add_form.paymentData.mchType">
              <el-option
                v-for="item in mch_type_list"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="add_form.paymentData.mchType === 1"
            label="支付商户号(Mch_Id):"
            prop="mchId"
          >
            <el-input
              v-model="add_form.paymentData.mchId"
              placeholder="请输入支付商户号"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="add_form.paymentData.mchType === 2"
            label="支付子商户号(Sub_mch_id):"
            prop="subMchId"
          >
            <el-input
              v-model="add_form.paymentData.sub_mch_id"
              placeholder="请输入子支付商户号"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="add_form.paymentData.mchType === 1"
            label="支付密钥(APIKEY):"
            prop="apiPartnerKey"
          >
            <el-input
              v-model="add_form.paymentData.apiPartnerKey"
              placeholder="请输入支付密钥"
            ></el-input>
            <div class="el-upload__tip">
              服务商的APIKEY,并不是子商户的APIKEY
            </div>
          </el-form-item>
          <el-form-item label="CERT证书文件:" prop="cert">
            <UploadFiles
              :file-list="cert_file"
              @handleRemove="certRemove"
              @uploadSuccess="upLoadCert"
              @upError="errorCert"
            ></UploadFiles>
            <div class="form-tip">
              下载证书cert.zip中的apiclient_cert.pem文件
            </div>
          </el-form-item>
          <el-form-item label="KEY密钥文件:" prop="key">
            <UploadFiles
              :file-list="key_file"
              @handleRemove="keyRemove"
              @uploadSuccess="upLoadKEY"
              @upError="errorKey"
            ></UploadFiles>
            <div class="form-tip">
              下载证书cert.zip中的apiclient_key.pem文件
            </div>
          </el-form-item>
          <el-form-item v-if="false" label="ROOT文件:" prop="root">
            <UploadFiles @uploadSuccess="upLoadRoot">
              <el-button slot="upbtn">选择上传</el-button>
            </UploadFiles>

            <span v-if="rootData.length > 0" class="uploaded">已上传</span>
            <span v-else class="uploadedErr">未上传</span>
            下载证书cert.zip中的rootca.pem文件,新下载证书无需上传此文件
          </el-form-item>
        </div>
        <div v-if="paymentName === '支付宝支付'">
          <el-form-item label="验证方式(SING_TYPE):" prop="waysIdentifying">
            <el-radio-group v-model="add_form.paymentData.waysIdentifying">
              <el-radio :label="2">RSA2</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="支付公钥(PUBLIC_KEY):" prop="alipayrsaPublicKey">
            <el-input
              v-model="add_form.paymentData.alipayrsaPublicKey"
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
            ></el-input>
            <div class="el-upload__tip">一行且不能有空格</div>
          </el-form-item>
          <el-form-item label="应用私钥(PRIVATE_KEY):" prop="rsaPrivateKey">
            <el-input
              v-model="add_form.paymentData.rsaPrivateKey"
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
            ></el-input>
            <div class="el-upload__tip">一行且不能有空格</div>
          </el-form-item>
        </div>
        <el-form-item label="客户类型屏蔽">
          <div v-if="!customer_type_list.length" style="text-align: center">
            暂无客户类型
          </div>
          <el-checkbox-group v-model="add_form.paymentData.notCustomerType">
            <el-checkbox
              v-for="(item, index) in customer_type_list"
              :key="index"
              :label="item.id"
            >
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="屏蔽开始次数:">
          <span style="margin-right: 10px">体验</span>
          <el-input-number
            v-model="add_form.paymentData.experienceNum"
            :controls="false"
            placeholder="次数"
          ></el-input-number>
          <span style="padding-left: 10px">次开始屏蔽</span>
          <p class="form-tip">一旦启用类型屏蔽超过次数则开始屏蔽</p>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="show_model = false">返回列表</el-button>
        <el-button type="primary" size="small" @click="addData">
          提 交
        </el-button>
      </span>
    </el-dialog>
    <AccountType
      v-if="account_show"
      :is-check="false"
      :is-show="account_show"
      :type="3"
      @cancel="account_show = false"
      @confirm="accountsel"
    />
  </container>
</template>

<script>
  import AccountType from "@/views/Finance/AccountType";
  import UploadFiles from "@/component/common/UploadFiles";
  import { apiUrl } from "@/config/settings";
  import {
    getAllPayment,
    savePaySetting,
    getPayment,
    delPayment,
    updateDefaultStatus,
    PaymentupdateEnableStatus,
    getAllCustomerSource,
  } from "@/api/System";
  export default {
    name: "Delivery",
    components: {
      UploadFiles,
      AccountType,
    },
    data() {
      const vBeginMoney = (rule, value, callback) => {
        if (this.add_form.paymentData.beginMoney === "") {
          callback(new Error("请输入期初余额"));
        } else {
          callback();
        }
      };
      const vAppid = (rule, value, callback) => {
        if (this.add_form.paymentData.appid === "") {
          callback(new Error("请输入微信小程序appid"));
        } else {
          callback();
        }
      };
      const mAppid = (rule, value, callback) => {
        if (!this.add_form.paymentData.mobileAppid) {
          callback(new Error("请输入移动应用appid"));
        } else {
          callback();
        }
      };
      const vmchId = (rule, value, callback) => {
        if (this.add_form.paymentData.mchId === "") {
          callback(new Error("请输入支付商户号(Mch_Id)"));
        } else {
          callback();
        }
      };
      const vapiPartnerKey = (rule, value, callback) => {
        if (this.add_form.paymentData.apiPartnerKey === "") {
          callback(new Error("请输入请输入支付密钥"));
        } else {
          callback();
        }
      };
      return {
        img_url: apiUrl.QINIU_URL,
        //  获取上传文件的数组
        keyData: [],
        certData: [],
        rootData: [],
        pageSize: 10,
        page: 1,
        total: 0,
        show_model: false,
        is_edit: false,
        paymentId: "",
        paymentName: "",
        img_list: [],
        add_form: {
          title: "",
          defaultStatus: 4,
          enableStatus: 5,
          paymentData: {
            beginMoney: 0,
            sorts: "",
            payType: "",
            appid: "",
            mobileAppid: "",
            mchId: "",
            mchType: 1,
            sub_mch_id: "",
            payWay: 1,
            apiPartnerKey: "",
            rsaPrivateKey: "", // 应用私钥
            alipayrsaPublicKey: "", // 公钥
            waysIdentifying: 2, // 验证方式
            cert: "",
            key: "",
            root: "",
            financeAccountId: "",
            financeAccountName: "",
            limit: "", //打款限额
            notCustomerType: [],
            experienceNum: "",
          },
        },
        appid: "",
        pay_list: [],
        rules: {
          title: [
            { required: true, message: "请输入支付名称", trigger: "blur" },
          ],
          beginMoney: [
            { required: true, validator: vBeginMoney, trigger: "blur" },
          ],
          appid: [{ required: true, validator: vAppid, trigger: "blur" }],
          mobileAppid: [{ required: true, validator: mAppid, trigger: "blur" }],
          mchId: [{ required: true, validator: vmchId, trigger: "blur" }],
          apiPartnerKey: [
            { required: true, validator: vapiPartnerKey, trigger: "blur" },
          ],
          subMchId: [{ required: true, validator: vmchId, trigger: "blur" }],
        },
        account_show: false,
        cert_file: [],
        key_file: [],
        mch_type_list: [
          {
            label: "普通商户",
            value: 1,
          },
          {
            label: "子商户",
            value: 2,
          },
        ],
        customer_type_list: [],
      };
    },
    async created() {
      await this.getData();
      await this.getAllCustomerSource();
    },
    activated() {
      if (this.$_isInit()) return;
      this.getData();
    },
    methods: {
      async getData() {
        const data = await getAllPayment({
          page: this.page,
          pageSize: this.pageSize,
        });

        this.pay_list = data.data;
        this.total = data.pageTotal;
      },
      //  上传密钥文件
      upLoadKEY(res, file, fileList) {
        this.add_form.paymentData.apiclient_key = res.data;
        this.key_file = [
          {
            name: file.name,
            url: res.data,
          },
        ];
      },
      errorKey() {
        this.add_form.paymentData.apiclient_key = "";
        this.key_file = [];
      },
      keyRemove() {
        this.add_form.paymentData.apiclient_key = "";
      },
      certRemove() {
        this.add_form.paymentData.apiclient_cert = "";
      },
      errorCert() {
        this.add_form.paymentData.apiclient_cert = "";
        this.cert_file = [];
      },
      //  上传cert文件
      upLoadCert(res, file, fileList) {
        this.add_form.paymentData.apiclient_cert = res.data;
        this.cert_file = [
          {
            name: file.name,
            url: res.data,
          },
        ];
      },
      //  上传root文件
      upLoadRoot(res, file, fileList) {
        this.rootData = fileList;
        this.add_form.paymentData.root = fileList.map((item) => {
          return `${this.img_url}/${item.response.key}`;
        });
      },
      async addData() {
        this.$refs["add_form"].validate(async (valid) => {
          if (valid) {
            if (
              !this.appid &&
              !["银行打款", "余额支付"].includes(this.add_form.title)
            ) {
              this.$confirm(
                "期初余额只能填写一次,提交后不能修改, 是否继续?",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              )
                .then(async () => {
                  let target = {};
                  target = await savePaySetting(this.paymentId, {
                    ...this.add_form,
                  });
                  const data = target;
                  this.show_model = false;
                  this.pageChange(1);
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "请修改期初余额",
                  });
                });
            } else {
              let target = {};
              target = await savePaySetting(this.paymentId, this.add_form);
              const data = target;
              this.show_model = false;
              this.pageChange(1);
            }
          }
        });
      },
      //  获取配置详情
      async getPayment(id, row) {
        this.paymentId = row.id;
        this.paymentName = row.title;
        const { data } = await getPayment(id);

        if (JSON.stringify(data) === "{}") {
          this.add_form = {
            ...this.add_form,
            title: row.title,
            logo: row.logo,
            defaultStatus: row.defaultStatus,
            enableStatus: row.enableStatus,
          };
        } else {
          const addform = {
            ...data,
            paymentData: {
              ...this.add_form.paymentData,
              ...data.paymentData,
            },
          };
          this.add_form = addform;
          this.appid = this.add_form.paymentData.appid;
          if (data.paymentData.apiclient_cert) {
            const name = data.paymentData.apiclient_cert.split("/")[2];
            this.cert_file = [
              {
                name: name,
                url: data.paymentData.apiclient_cert,
              },
            ];
          }
          if (data.paymentData.apiclient_key) {
            const name = data.paymentData.apiclient_key.split("/")[2];
            this.key_file = [
              {
                name: name,
                url: data.paymentData.apiclient_key,
              },
            ];
          }
        }
      },
      openModel(isEdit, row) {
        this.show_model = true;
        this.is_edit = isEdit;
        if (row) {
          this.getPayment(row.id, row);
        }
      },
      sizeChange(size) {
        this.pageSize = size;
        this.pageChange(1);
      },
      pageChange(page) {
        this.page = page;
        this.getData();
      },
      delData(id) {
        this.$confirm("确定要删除该支付方式吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const data = await delPayment(id);

          await this.getData();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        });
      },
      defaultData(id) {
        this.$confirm("确定要将该支付方式设为默认吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const data = await updateDefaultStatus(id, {
            defaultStatus: "5",
          });

          await this.getData();
          this.$message({
            type: "success",
            message: "设置成功!",
          });
        });
      },
      async statusSet(val, row) {
        try {
          const data = await PaymentupdateEnableStatus(row.id, {
            enableStatus: val,
          });
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        } catch (e) {
          await this.getData();
        }
      },
      accountsel(val) {
        this.add_form.paymentData.financeAccountId = val[0].id;
        this.add_form.paymentData.financeAccountName = val[0].bankName;
      },
      // 获取客户类型
      async getAllCustomerSource() {
        const data = await getAllCustomerSource({
          page: 1,
          pageSize: 99,
        });
        this.customer_type_list = data.data;
      },
    },
  };
</script>

<style scoped>
  .el-upload__tip {
    color: #a6a9ad;
    font-size: 8px;
    margin: 0;
  }
  .uploaded {
    display: inline-block;
    background-color: #53c94f;
    font-size: 8px;
    color: #ffffff;
    width: 50px;
    height: 15px;
    text-align: center;
    line-height: 15px;
    border-radius: 2px;
  }
  .uploadedErr {
    display: inline-block;
    background-color: #ed5d5c;
    font-size: 8px;
    color: #ffffff;
    width: 50px;
    height: 15px;
    text-align: center;
    line-height: 15px;
    border-radius: 2px;
  }
</style>
