<template>
  <div class="page-wrap page-wrap-account">
    <tool-bar
      :text="['name']"
      :label="['公众号名称']"
      v-model:loading="searching"
      @confirm="onSearch"
      @cancel="onCancel"
    >
    </tool-bar>
    <a-table
      rowKey="id"
      :loading="loading"
      :pagination="tablePageOptions"
      :columns="columns"
      :scroll="{ y: 600}"
      bordered
      :data-source="list"
      @change="onLoadOfficials"
    >
      <template #status="{ text }">
        <p>{{ text == 0 ? "关闭" : "开启" }}</p>
      </template>
      <template #time="{ record }">
        <p>起:{{ record.start_time }}</p>
        <p>止:{{ record.end_time }}</p>
      </template>
      <template #action="{ record }">
        <a-button type="primary" @click="initBackData(record)">
          回传配置
        </a-button>
        <a-button style="margin-left: 5px" @click="getLogs(record)">
          回传日志
        </a-button>
      </template>
    </a-table>
    <!-- 站点回传配置drawer -->
    <a-modal
      v-model:visible="visible"
      title="回传配置"
      width="40%"
      class="drawer-back-config"
      @ok="handleOk"
      centered="true"
    >
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ offset: 1, span: 11 }">
        <a-form-item label="回传条件">
          <a-select
            style="width: 150px"
            size="small"
            v-model:value="popForm[currentTab].condition"
          >
            <a-select-option
              :value="item.name"
              v-for="item in popForm[currentTab].report_conditions"
              :key="item.name"
            >
              {{ item.desc }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="回传比例">
          <a-input
            v-model:value="ad_config.rate"
            size="small"
            style="width: 150px"
            type="number"
            placeholder="回传比例"
            :min="0"
            :max="100"
          >
            <template #suffix>
              <a-tooltip title="比例0-100">
                <info-circle-outlined style="color: rgba(0, 0, 0, 0.45)" />
              </a-tooltip>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="回传付费最低金额">
          <a-input
            v-model:value="ad_config.lowestMoney"
            size="small"
            style="width: 150px"
            type="number"
            :min="0"
          >
            <template #suffix>
              <a-tooltip title="元">
                <span>元</span>
              </a-tooltip>
            </template>
          </a-input>
        </a-form-item>
      </a-form>
    </a-modal>
    <!--回传日志-->
    <a-drawer
      title="回传日志"
      placement="right"
      :closable="true"
      width="80%"
      v-model:visible="visibleLog"
    >
      <log-list :visible="visibleLog" :channel_id="curChannel_id"> </log-list>
    </a-drawer>
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  inject,
  onMounted,
  reactive,
  ref,
  toRefs,
} from "vue";
import EditableCell from "@/components/edit-cell/index.vue";
import ToolBar from "@/components/tool-bar/index.vue";
import useApp from "@/hooks/useApp";
import usePagination from "@/hooks/usePagination";
import logList from "./log.vue";
import { TableColumnOfAccount } from "@/views/_pageOptions/table-account";
import {
  getOfficialAccounts,
  getOfficialBackConfig,
} from "@/api";
import { IOfficials, PlanBack } from "#/api";
import { message } from "ant-design-vue";
import { InfoCircleOutlined } from "@ant-design/icons-vue";
import {
  setOfficialBackConfig,
} from "../../api/index";

const Account = defineComponent({
  components: {
    ToolBar,
    EditableCell,
    InfoCircleOutlined,
    logList,
  },
  setup() {
    let { loading, meta, tablePageOptions } = usePagination();
    const { store } = useApp();
    const state = reactive({
      platforms: computed(() => store.getters.platforms),
      list: ref<IOfficials[]>([]),
      columns: TableColumnOfAccount,
      searching: false,
      moduleType: ref<any>({
        channel: "按站点回传",
        ad: "按计划回传",
      }),
      query: {
        official_name: "",
        platform: "",
        page: 1,
        // report_status: -1,
        report_module: "",
      },
      hasPopFormData: false,
      popForm: ref<any[]>([
        {
          id: 0,
          back_on: false,
          rate: 0,
          condition: "",
          price: 30,
          float_rate: 0,
          desc: "",
        },
      ]),
      ad_config: {
        channel_id: "",
        id: 0,
        rate: 0,
        lowestMoney: 30,
        condition: "current_day_register_first_recharge",
      },
      report_module: "ad",
      report_channel_id: 0,
      showConfig: false,
      visible: false,
      saving: false,
      visibleLog: false,
      curChannel_id: 0,
      currentTab: 0,
    });

    const onSearch = (fields: Record<string, string>) => {
      const { name } = fields;
      state.query.official_name = name;
      onLoadOfficials();
    };
    //取消时触发
    const onCancel = () => {
      state.query.report_module = "";
      onSearch({ name: "" });
      onLoadOfficials();
    };

    const onLoadOfficials = (query?: { current: number }) => {
      let params = JSON.parse(JSON.stringify(state.query));
      if (query) params.page = query.current;
      params.report_platform = "kuaishou";
      loading.value = true;
      // if (state.query.report_status === -1) delete params.report_status;
      if (state.query.report_module === "") delete params.report_module;
      getOfficialAccounts(params).then(({ data }) => {
        state.list = data.list;
        meta.value = data.meta;
        loading.value = false;
        state.searching = false;
      });
    };
    //获得公众号"/userOfficialAccounts"
    onMounted(onLoadOfficials);

    const initBackData = async (item: IOfficials) => {
      try {
        const { data } = await getOfficialBackConfig(
          item.channel_id,
          "kuaishou"
        );
        if (data.channel_configs[0].id) {
          state.ad_config.id = +data.channel_configs[0].id;
        }
        state.ad_config.channel_id = data.ad_config.channel_id;
        state.ad_config.rate = data.channel_configs[0].rate;
        state.report_module = data.report_module;
        state.showConfig = data.report_module == "ad" ? false : true;
        state.report_channel_id = +data.channel_id;
        let list = data.channel_configs.map((r: PlanBack) => {
          r.price = r.extra?.price;
          r.float_rate = r.extra?.float_rate;
          r.back_on = !!Number(r.back_on);
          return r;
        });
        list.length > 0
          ? (state.hasPopFormData = true)
          : (state.hasPopFormData = false);
        state.popForm = list;
        state.visible = true;
      } catch (error) {
        console.log("error happened in get back plan data:", error.message);
      }
    };
    const handlechange = (value: string) => {
      state.ad_config.condition = value;
    };
    const onTabChange = (key: number) => {
      state.currentTab = key;
    };

    //保存站点回传比例

    const SaveConfig = async () => {
      state.visible = false;
      let data = {
        rate: state.ad_config.rate,
        condition: state.popForm[state.currentTab].condition,
        price: state.ad_config.lowestMoney,
        report_platform: "kuaishou",
        id: state.ad_config.id,
      };
      const res = await setOfficialBackConfig(data);
      state.ad_config.lowestMoney = 30;
      if (res.data.success == 0) {
        message.success("保存成功");
      }
      onLoadOfficials();
    };
    //确定时提交表单
    const handleOk = () => {
      SaveConfig();
    };
    return {
      ...toRefs(state),
      loading,
      tablePageOptions,
      onSearch,
      onCancel,
      onLoadOfficials,
      initBackData,
      onTabChange,
      handleOk,
      handlechange,
    };
  },
  methods: {
    getLogs(record: any) {
      this.curChannel_id = record.channel_id;
      this.visibleLog = true;
    },
  },
});

export default Account;
</script>

<style lang="scss">
.drawer-back-config {
  .wrap-box {
    margin-bottom: 15px;

    .title {
      font-size: 16px;
      color: #333;
      font-weight: bold;
      margin-bottom: 5px;
    }
  }
}
</style>
