<template>
  <div>
    <Search :search="search" :reset="reset">
      <template v-slot:body>
        <el-form-item label="cp名称" prop="cp" v-if="!isShowCp">
          <el-select v-model="query.cp_name" filterable remote clearable :remote-method="remoteMethod"
            placeholder="选择版权方">
            <el-option v-for="item in cpoptions" :key="item.cp_id" :label="item.cp_name" :value="item.cp_name" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="cp_company">
          <el-date-picker unlink-panels clearable @change="timeChange" format="YYYY/MM" value-format="YYYY-MM"
            v-model="query.time" type="monthrange" range-separator="To" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
      </template>
      <template v-slot:extra_button>
        <el-button type="primary" @click="dataExport" size="default">
          <!-- <Icon name="document-arrow-up" className="w-4 h-4 mr-1 -ml-1" /> -->
          导出
        </el-button>
      </template>
    </Search>
    <div class="table-default">
      <el-table :data="tableData" class="mt-3" v-loading="loading">
        <el-table-column prop="month" label="月份" />
        <el-table-column prop="cp_id" label="cpid" />
        <el-table-column prop="cp_name" label="cp名称" />
        <el-table-column prop="cp_company" label="所属公司" />
        <el-table-column prop="book_num" label="结算短剧量" />
        <el-table-column prop="final_amount" label="结算金额" />
        <el-table-column label="结算情况" v-action="'cpManage.CpSubscribeStatisticData.saveFinalState'">
          <template #default="scope">
            <el-button v-if="scope.row.final_state == 'notCheck'" type="primary" size="default"
              @click="finalStateChange($event, scope.row)">点击结算</el-button>
            <el-tag v-else type="success" size="default" effect="dark">已结算</el-tag>

          </template>
        </el-table-column>
        <el-table-column prop="final_time" label="结算日期" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="exportSingle(scope.row)">导出</el-button><br />
          </template>
        </el-table-column>
      </el-table>
      <Paginate />
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  computed,
  onMounted,
  ref
} from 'vue';
import {
  useGetList
} from '@/hook/curd/useGetList';
import moment from 'moment';
import { cpOptions, saveFinalState, subscribeStatisticDataMonthList, exportListCpMonthFinalAmount } from '@/api/cp/index';
import { exportExcel } from '@/utils/exportExcel';
import { useUserStore } from '@/stores/modules/user';
const userStore = useUserStore();
// cp方用户不能有版权方搜索
const isShowCp = computed(() => {
  console.log(userStore.getRoles, 'getRoles');
  return userStore.getRoles?.some(el => (el?.identify == 'cp'))
})

const api = 'cpManage/cp/subscribeStatisticData/monthList';
// const start_date = moment().startOf('month').format('YYYY-MM')
// const end_date = moment().endOf('month').format('YYYY-MM')
const exportSingle = (item) => {
  console.log(item);
  const params = {
    cp_name: item.cp_name,
    month: item.month
  }
  exportListCpMonthFinalAmount(params).then(res => {
    console.log(res);
    const data = ref()
    const titleObj = {
      "书籍ID": "bid",
      "书籍名称": "book_name",
      "应结算金额": "final_amount",
      "CP名称": "cp_name",
      "月份": "month",
    };
    data.value = res.data
    if (data.value.length > 0) {
      exportExcel(data.value, `(${item.cp_name})cp结算(月份)${moment().format('YYYY-MM-DD HH:mm:ss')}`, titleObj, "cp结算(月份)");
    } else {
      ElMessage.warning('暂无数据')
    }
  })
}

const dataExport = () => {
  let exportTableData = ref([])
  subscribeStatisticDataMonthList({ is_export: 1, ...query.value }).then(res => {
    console.log(res);
    exportTableData.value = res.data
    console.log(res, 'exportTableData', exportTableData.value);
    const titleObj = {
      "月份": "month",
      "cpid": "cp_id",
      "cp名称": "cp_name",
      "所属公司": "cp_company",
      "结算书本量": "book_num",
      "结算金额": "final_amount",
      "结算情况": "final_state_str",
      "结算日期": "final_time",
    };
    if (tableData.value.length > 0) {
      exportExcel(exportTableData.value, `cp结算${moment().format('YYYY-MM-DD HH:mm:ss')}`, titleObj, "cp结算");
    } else {
      ElMessage.warning('暂无数据')
    }
  })
}

const finalStateChange = (e, data) => {
  saveFinalState({ id: data.id, final_state: 'done' }).then(res => {
    const r = res.data;
    const code = r.code;
    const message = r.message;
    if (code === 1e4) {
      ElMessage.success(message || '设置成功');
      return r;
    }
  });
  search()
  reset()
}

const timeChange = (e) => {
  if (query.value.time) {
    const timeArr = toRaw(e);
    query.value.start_month = timeArr[0]
    query.value.end_month = timeArr[1]
  } else {
    delete query.value.start_month
    delete query.value.end_month
  }

}

const { data, query, search, reset, loading } = useGetList(api, true);
let cpoptions = ref([]);

const tableData = computed(() => data.value?.data);
const remoteMethod = (query: string) => {
  if (query) {
    console.log(66666);
    initCpOtion({ cp_name: query })
  } else {
    initCpOtion({})
  }
}
const initCpOtion = (params: object) => {
  cpOptions(params).then(res => {
    cpoptions.value = res.data
  })
}

onMounted(() => {
  // query.value.time = [start_date, end_date];
  // query.value.start_date = start_date;
  // query.value.end_date = end_date;
  initCpOtion({})
  search();
});
</script>
