<template>
  <div class="bind-page">
    <div style="display: flex; align-items: center; justify-content: space-between">
      <div>
        <a-button class="small left" @click="onSetBackShowTable">
          <template #icon>
            <LeftOutlined />
          </template>
        </a-button>
        <a-button class="small right">
          <template #icon>
            <MenuUnfoldOutlined />
          </template>
        </a-button>
      </div>

      <div>
        <a-button type="primary" block @click="showModal" v-if="query && query.isShow">新建支付通道</a-button>
      </div>
    </div>
    <div style="margin-top: 10px">
      <a-table :columns="columns" :data-source="list" :pagination="false" v-if="isShowTable">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'wx' && record.paytype == '1'">
            <div>
              <CheckCircleFilled style="font-size: 25px; color: rgb(12, 191, 33)"></CheckCircleFilled>
            </div>
          </template>
          <template v-else-if="column.key === 'zfb' && record.paytype == '2'">
            <div>
              <CheckCircleFilled style="font-size: 25px; color: rgb(12, 191, 33)"></CheckCircleFilled>
            </div>
          </template>
          <template v-else-if="column.key === 'tags'">
            <span>
              <a-tag v-for="tag in record.tags" :key="tag" :color="
                tag === 'loser'
                  ? 'volcano'
                  : tag.length > 5
                    ? 'geekblue'
                    : 'green'
              ">
                {{ tag.toUpperCase() }}
              </a-tag>
            </span>
          </template>
          <template v-else-if="column.key === 'status'">
            <div v-if="record.status === 0">
              <span class="ml20" style="color: rgba(12, 191, 33, 1)">良好</span>
            </div>
            <div v-else-if="record.status === 1">
              <span class="ml20" style="color: rgb(250, 116, 116)">预警</span>
            </div>
          </template>
          <template v-else-if="column.key === 'weight'">
            <a-input-number id="inputNumber" v-model:value="record.weight" :min="1" :max="10"
              @blur="onChangeWeight(record)" />
            <span>1-10</span>
          </template>
          <template v-else-if="column.key === 'ref'">
            <span>
              <a-button danger @click="onSetShowTable(record)">配置</a-button>
            </span>
            <span>
              <a-button danger style="margin-left: 10px" @click="onDis(record)">禁用</a-button>
            </span>
          </template>
        </template>
      </a-table>
      <div v-else>
        <a-form :label-col="{ span: 2 }" :wrapper-col="{ span: 12 }">
          <a-form-item label="通道名称" has-feedback labelAlign="left" v-bind="validateInfos.name">
            <a-input v-model:value="modelRef.name" placeholder="请输入通道名称" />
          </a-form-item>
          <a-form-item label="appid:" has-feedback labelAlign="left" v-bind="validateInfos.appid">
            <a-input v-model:value="modelRef.appid" placeholder="请输入appid" />
          </a-form-item>
          <a-form-item label="商户id:" has-feedback labelAlign="left" v-bind="validateInfos.privatekey">
            <a-input v-model:value="modelRef.privatekey" placeholder="请输入商户id" />
          </a-form-item>
          <a-form-item label="密钥:" has-feedback labelAlign="left" v-bind="validateInfos.alipaypublickey">
            <a-input v-model:value="modelRef.alipaypublickey" placeholder="请输入密钥" />
          </a-form-item>
          <!-- <a-form-item
            label="域名配置:"
            has-feedback
            labelAlign="left"
            v-bind="validateInfos.server_url"
          >
            <a-input
              v-model:value="modelRef.server_url"
              placeholder="请输入域名配置"
            />
          </a-form-item> -->
          <a-form-item>
            <a-button type="primary" @click="onSubmit">保存</a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
    <a-modal v-model:visible="visible" title="支付通道名称" @ok="handleOk" :footer="null">
      <a-form :model="formState" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" autocomplete="off"
        @finish="onFinish" @finishFailed="onFinishFailed">
        <a-form-item label="支付通道名称" name="name" :rules="[{ required: true, message: '请输入新建支付通道名称' }]">
          <a-input v-model:value="formState.name" />
        </a-form-item>
        <p class="title">建议用该微信商户号主体名称作为通道名称</p>
        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit" @click="onCreate">确认</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { defineExpose, ref, reactive, computed, toRaw, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Form } from "ant-design-vue";
import {
  LeftOutlined,
  MenuUnfoldOutlined,
  CheckCircleFilled,
} from "@ant-design/icons-vue";
import {
  onZfbPay,
  onWxPay,
  onfindAli,
  onfindWX,
  onUpdate,
  onUpdateWX,
} from "@/api/index";
import { message } from "ant-design-vue";
import { getUid } from "@/utils/userInfo";
interface FormState {
  name: String;
}
interface AppFormStateWX {
  uid: String;
  appid: String;
  name: String;
  mchid: String;
  mchkey: String;
  // server_url: String;
}
interface AppFormStateAl {
  uid: String;
  appid: String;
  privatekey: String;
  alipaypublickey: String;
  name: String;
  // server_url: String;
}
const useForm = Form.useForm;
const columns = ref<any>([
  {
    title: "支付通道名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "微信",
    dataIndex: "wx",
    key: "wx",
  },
  {
    title: "支付宝",
    dataIndex: "zfb",
    key: "zfb",
  },
  {
    title: "状态",
    key: "status",
    dataIndex: "status",
  },
  {
    title: "权重",
    key: "weight",
  },
  {
    title: "操作",
    key: "ref",
  },
]);

const list = ref([]);
const route = useRoute();
const router = useRouter();
const status = ref(0);
let modelRef = reactive<any>({});
let rulesRef = reactive<any>({});

const query: any = computed({
  get: () => {
    return route.query;
  },
  set: () => {
    return route.query;
  },
});
const dataFrom = ref<any>({});

const onChangeWeight = async (record: any) => {
  const prarms = {
    uid: getUid(),
    ...record,
  };
  let data: any = {};

  if (query.value.paytype == 1) {
    data = await onUpdateWX(JSON.stringify(prarms));
  } else if (query.value.paytype == 2) {
    data = await onUpdate(JSON.stringify(prarms));
  }

  if (data.state == 1) {
    message.success("修改成功");
    await init();
  }
};

const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef);
const onSubmit = async () => {
  validate()
    .then(async () => {
      let data: any = {};
      const prarms = {
        paytype: query.value.paytype,
        uid: getUid(),
        ...toRaw(modelRef),
      };
      if (status.value === 1) {
        dataFrom.value = {
          amount: dataFrom.value.amount,
          id: dataFrom.value.id,
          paystate: dataFrom.value.paystate,
          paytype: dataFrom.value.paytype,
          status: dataFrom.value.status,
          weight: dataFrom.value.weight,
          mchid: toRaw(modelRef).mchid,
          mchkey: toRaw(modelRef).mchkey,
          ...toRaw(modelRef),
        };
        if (query.value.paytype == "1") {
          data = await onUpdateWX(JSON.stringify(dataFrom.value));
        } else if (query.value.paytype == "2") {
          data = await onUpdate(JSON.stringify(dataFrom.value));
        }
        if (data.state === 1) {
          isShowTable.value = true;
          message.success(data.message, 10);
        } else {
          message.warning(data.message, 10);
        }
        await init();
      } else {
        if (query.value.paytype == 1) {
          data = await onWxPay(prarms);
        } else if (query.value.paytype == 2) {
          data = await onZfbPay(prarms);
        }
        if (data.state === 1) {
          isShowTable.value = true;
          message.success(data.message, 10);
        } else {
          message.warning(data.message, 10);
        }
        await init();
      }
    })
    .catch((err) => {
      console.log("error", err);
    });
};
const visible = ref<boolean>(false);
const isShowTable = ref<boolean>(true);
const showModal = () => {
  visible.value = true;
};
const formState = reactive<FormState>({
  name: "",
});

const handleOk = (e: MouseEvent) => {
  visible.value = false;
};
const onFinish = (values: any) => {
  console.log("Success:", values);
};

const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};
const onSetShowTable = async (data: any) => {
  console.log(data, "data");

  status.value = 1;
  isShowTable.value = false;
  if (query.value.paytype == 1) {
    const { mchid, mchkey, appid, name } = data;
    const uid: any = getUid();
    modelRef.privatekey = mchid;
    modelRef.alipaypublickey = '';
    modelRef.appid = appid;
    modelRef.name = name;
    // modelRef.server_url =server_url
    modelRef.uid = uid;
  } else {
    const { alipaypublickey, privatekey, appid, payname } = data;
    const uid: any = getUid();
    modelRef.alipaypublickey = '';
    modelRef.privatekey = privatekey;
    modelRef.appid = appid;
    modelRef.name = payname;
    // modelRef.server_url =server_url
    modelRef.uid = uid;
  }
  
  dataFrom.value = data;
};
const onCreated = () => {
  isShowTable.value = false;
};
const onSetBackShowTable = () => {
  router.go(-1);
};
const onDis = (data: any) => {
  console.log(data, "data");
};
const onCreate = () => {
  modelRef.name = formState.name;
  visible.value = !visible.value;
  onCreated();
};
const init = async () => {
  const uid: any = getUid();
  let data: any = {};
  if (query.value.paytype == 1) {
    data = await onfindWX(uid);
  } else if (query.value.paytype == 2) {
    data = await onfindAli(uid);
  }
  list.value = data.data;
  return list;
};
onMounted(async () => {
  await init();
  let rulesRef;
  let modelRef;
  if (query.value.paytype == 1) {
    columns.value = [
      {
        title: "支付通道名称",
        dataIndex: "name",
        key: "name",
      },
      {
        title: "微信",
        dataIndex: "wx",
        key: "wx",
      },
      {
        title: "状态",
        key: "status",
        dataIndex: "status",
      },
      {
        title: "权重",
        key: "weight",
      },
      {
        title: "操作",
        key: "ref",
      },
    ];
    rulesRef = reactive({
      mchid: [
        {
          required: true,
          message: "请输入商户id",
        },
      ],
      mchkey: [
        {
          required: true,
          message: "请输入密钥",
        },
      ],
      name: [
        {
          required: true,
          message: "请输入通道名称",
        },
      ],
      // server_url: [
      //   {
      //     required: true,
      //     message: "请输入server_url",
      //   },
      // ],
      appid: [
        {
          required: true,
          message: "请输入appid",
        },
      ],
    });
    modelRef = reactive<AppFormStateWX>({
      mchid: "",
      mchkey: "",
      uid: "",
      appid: "",
      name: "",
      // server_url: "",
    });
  } else {
    columns.value = [
      {
        title: "支付通道名称",
        dataIndex: "name",
        key: "name",
      },
      {
        title: "支付宝",
        dataIndex: "zfb",
        key: "zfb",
      },
      {
        title: "状态",
        key: "status",
        dataIndex: "status",
      },
      {
        title: "权重",
        key: "weight",
      },
      {
        title: "操作",
        key: "ref",
      },
    ];
    rulesRef = reactive({
      alipaypublickey: [
        {
          required: true,
          message: "请输入商户id",
        },
      ],
      privatekey: [
        {
          required: true,
          message: "请输入密钥",
        },
      ],
      name: [
        {
          required: true,
          message: "请输入通道名称",
        },
      ],
      // server_url: [
      //   {
      //     required: true,
      //     message: "请输入server_url",
      //   },
      // ],
      appid: [
        {
          required: true,
          message: "请输入appid",
        },
      ],
    });
    modelRef = reactive<AppFormStateAl>({
      alipaypublickey: "",
      privatekey: "",
      uid: "",
      appid: "",
      name: "",
      // server_url: "",
    });
  }
  return { rulesRef, modelRef, columns };
});
defineExpose({
  list,
  columns,
  visible,
  route,
  showModal,
  handleOk,
  formState,
  onFinish,
  onFinishFailed,
  isShowTable,
  onSetShowTable,
  onCreated,
  validateInfos,
  resetFields,
  onSubmit,
  onCreate,
  query,
  onChangeWeight,
  onDis,
  modelRef,
});
</script>
<style lang="less" scoped>
.bind-page {
  .small {
    border: none;
    height: 30px;
    width: 50px;
  }

  .left {
    border-left: 1px solid rgb(236, 236, 236);
    border-top: 1px solid rgb(236, 236, 236);
    border-bottom: 1px solid rgb(236, 236, 236);
    border-right-width: 80%;
    border-right: 1px solid rgb(236, 236, 236);
    border-bottom-left-radius: 25px;
    border-top-left-radius: 25px;
  }

  .right {
    border-right: 1px solid rgb(236, 236, 236);
    border-top: 1px solid rgb(236, 236, 236);
    border-bottom: 1px solid rgb(236, 236, 236);
    border-bottom-right-radius: 25px;
    border-top-right-radius: 25px;
  }
}
</style>
<style scoped>
.title {
  text-align: center;
  font-family: SourceHanSansSC;
  font-weight: 400;
  font-size: 13px;
  color: rgba(190, 190, 190, 1);
  font-style: normal;
  letter-spacing: 0px;
  line-height: 19px;
  text-decoration: none;
}
</style>