<template>
  <div class="page-wrap page-wrap-account">
    <tool-bar
      :text="['name']"
      :label="['公众号名称']"
      v-model:loading="searching"
      @confirm="onSearch"
      @cancel="onCancel"
    >
      <!-- <div class="tool-bar-item">
        <p class="label">小说平台</p>
        <a-select class="full-width" v-model:value="query.platform">
          <a-select-option
            v-for="platform in platforms"
            :key="platform.value"
            :value="platform.value"
            >{{ platform.label }}</a-select-option
          >
        </a-select>
      </div>-->
      <!-- <div class="tool-bar-item">
        <p class="label">回传状态</p>
        <a-select class="full-width" v-model:value="query.report_status">
          <a-select-option :key="-1" :value="-1">全部</a-select-option>
          <a-select-option :key="1" :value="1">开启</a-select-option>
          <a-select-option :key="0" :value="0">关闭</a-select-option>
        </a-select>
      </div>-->
      <div class="tool-bar-item">
        <p class="label">回传方式</p>
        <a-select class="full-width" v-model:value="query.report_module">
          <a-select-option key="all" :value="''">全部</a-select-option>
          <a-select-option key="channel" value="channel">按站点回传</a-select-option>
          <a-select-option key="ad" value="ad">按计划回传</a-select-option>
        </a-select>
      </div>
    </tool-bar>
    <a-table
      rowKey="id"
      :loading="loading"
      :pagination="tablePageOptions"
      :columns="columns"
      :scroll="{ y: 600 }"
      bordered
      :data-source="list"
      @change="onLoadOfficials"
    >
      <!-- <template #rate="{ text, record }">
        <editable-cell
          :text="`${text}`"
          title="回传比例"
          :maxValue="100"
          :minValue="1"
          @change="(val) => onCellChange(record, 'rate', val)"
        />
      </template>-->
      <template #module="{ record }">
        <p>{{ moduleType[record.report_module] }}</p>
      </template>
      <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>
      </template>
      <!-- <template #operte="{ text, record }">
        <p
          v-clipboard:copy="record.fans_add_monitor_link"
          v-clipboard:success="copySuccess"
        >
          <a>复制监测链接</a>
        </p>
      </template>-->
    </a-table>
    <!-- 站点回传配置drawer -->
    <a-drawer v-model:visible="visible" title="回传配置" width="40%" class="drawer-back-config">
      <div class="wrap-box">
        <p class="title">回传方式</p>
        <a-radio-group
          v-model:value="report_module"
          @change="showConfig = report_module == 'ad' ? false : true"
        >
          <a-radio value="ad">计划</a-radio>
          <a-radio value="channel">站点</a-radio>
        </a-radio-group>
        <a href="javascript:;" @click="onReportModuleChange">保存</a>
      </div>
      <div class="wrap-box" v-show="!showConfig">
        <p class="title">按计划回传配置</p>
        <a-form :label-col="{ span: 6 }" :wrapper-col="{ offset: 1, span: 11 }">
          <a-form-item label="回传比例">
            <a-input-number v-model:value="ad_config.rate" />
          </a-form-item>
          <a-form-item :wrapper-col="{ offset: 7 }">
            <a-button type="primary" @click="onRateChange">保存</a-button>
          </a-form-item>
        </a-form>
      </div>
      <div class="wrap-box" v-show="showConfig">
        <p class="title">按站点回传配置</p>
        <a-tabs size="small" @change="onTabChange">
          <a-tab-pane v-for="(d, i) in popForm" :key="i" :tab="d.desc"></a-tab-pane>
        </a-tabs>
        <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-switch
              v-model:checked="popForm[currentTab].back_on"
              checked-children="开"
              un-checked-children="关"
            />
          </a-form-item>
          <a-form-item label="回传比例">
            <a-input
              v-model:value="popForm[currentTab].rate"
              size="small"
              style="width: 150px"
              type="number"
              placeholder="回传比例"
            >
              <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="popForm[currentTab].back_platform"
              disabled
              size="small"
              style="width: 150px"
            />
          </a-form-item>
          <a-form-item label="回传付费最低金额" v-if="popForm[currentTab].report_type === 'recharge'">
            <a-input
              v-model:value="popForm[currentTab].price"
              size="small"
              style="width: 150px"
              type="number"
              placeholder="回传付费最低金额"
            />
          </a-form-item>
          <a-form-item label="浮动回传比例">
            <a-input
              v-model:value="popForm[currentTab].float_rate"
              size="small"
              style="width: 150px"
              type="number"
              placeholder="浮动回传比例"
            >
              <template #suffix>
                <a-tooltip title="浮动比例小于固定回传比例">
                  <info-circle-outlined style="color: rgba(0, 0, 0, 0.45)" />
                </a-tooltip>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item :wrapper-col="{ offset: 7 }">
            <a-button
              :disabled="!hasPopFormData"
              :loading="saving"
              type="primary"
              @click="onSaveConfig"
            >保存</a-button>
          </a-form-item>
        </a-form>
      </div>
    </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 { TableColumnOfAccount } from "@/views/_pageOptions/table-account";
import {
  getOfficialAccounts,
  setChannelRate,
  getOfficialBackConfig,
} from "@/api";
import { IOfficials, PlanBack } from "#/api";
import { message } from "ant-design-vue";
import { InfoCircleOutlined } from "@ant-design/icons-vue";
import {
  setOfficialBackConfig,
  onUpdateOfficialReportType,
} from "../../api/index";

const Account = defineComponent({
  components: {
    ToolBar,
    EditableCell,
    InfoCircleOutlined,
  },
  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: 0,
          float_rate: 0,
          desc: "",
        },
      ]),
      ad_config: {
        channel_id: "",
        id: 0,
        rate: 0,
      },
      report_module: "ad",
      report_channel_id: 0,
      showConfig: false,
      visible: false,
      saving: false,
      currentTab: 0,
    });

    const onSearch = (fields: Record<string, string>) => {
      const { name } = fields;
      state.query.official_name = name;
      onLoadOfficials();
    };
    const onCancel = () => {
      // state.query.report_status = -1;
      state.query.report_module = "";
      onSearch({ name: "" });
    };

    const onLoadOfficials = (query?: { current: number }) => {
      let params = JSON.parse(JSON.stringify(state.query));
      if (query) params.page = query.current;
      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;
      });
    };

    onMounted(onLoadOfficials);

    const initBackData = async (item: IOfficials) => {
      try {
        const { data } = await getOfficialBackConfig(item.channel_id);
        state.ad_config.channel_id = data.ad_config.channel_id;
        state.ad_config.id = data.ad_config.id;
        state.ad_config.rate = data.ad_config.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:");
      }
    };

    const onTabChange = (key: number) => {
      state.currentTab = key;
    };

    const onRateChange = () => {
      const { rate, channel_id } = state.ad_config;
      setChannelRate({ rate, channel_id }).then((res) => {
        onLoadOfficials();
        message.success("修改回传比例成功！");
        state.visible = false;
      });
    };
    const onReportModuleChange = () => {
      // state.showConfig = state.report_module == "ad" ? false : true;
      onUpdateOfficialReportType(
        state.report_channel_id,
        state.report_module
      ).then((_) => {
        onLoadOfficials();
        message.success("修改回传方式成功！");
      });
    };

    const onSaveConfig = () => {
      let { id, back_on, rate, condition, price, float_rate } =
        state.popForm[state.currentTab];
      if (float_rate && float_rate >= rate) {
        message.error("浮动比例必须小于固定回传比例");
        return;
      }

      state.saving = true;

      let data = {
        id,
        back_on: Number(back_on),
        rate,
        condition,
        price,
        float_rate,
      };

      setOfficialBackConfig(data)
        .then((_) => {
          onLoadOfficials();
          message.success("保存成功");
          state.visible = false;
        })
        .catch((e) => {
          message.error(e.message || e.msg || "系统错误");
        })
        .finally(() => {
          state.saving = false;
        });
    };

    return {
      ...toRefs(state),
      loading,
      tablePageOptions,
      onSearch,
      onCancel,
      onLoadOfficials,
      initBackData,
      onTabChange,
      onRateChange,
      onSaveConfig,
      onReportModuleChange,
    };
  },
  methods: {
    copySuccess() {
      this.$message.success("复制成功");
    },
    onCellChange(record: any, dataIndex: string, value: string) {
      setChannelRate({ rate: value, channel_id: record.channel_id }).then(
        (res) => {
          this.$message.success("修改回传比例成功！");
        }
      );
    },
  },
});

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>
