<template>
  <div>
    <crud-template :ref="(el) => (crudRef = el)" class="as-weight" :home-data="field" :table-data="tableData"
      @btnSearch="btnSearch" @generateAeport="generateAeport" @importData="importData" @refreshLeft="refreshLeft"
      @CurrentChange="handleCurrentChange" @download="downloadHandle" @pageSizeChange="(val) => {
      field.paging.currentPage = 1
      field.paging.pageSize = val
      getList()
    }">
      <template #search>
        <el-input maxlength="60" v-trim clearable v-model="searchForm.promotionChannels" style="width: 200px;"
          placeholder="请输入推广渠道" />
        <el-input maxlength="60" v-trim clearable v-model="searchForm.productType" style="width: 200px;"
          placeholder="请输入产品类型" />
        <!-- <el-select clearable  v-model="searchForm.productType" style="width: 180px" placeholder="请选择产品类型" filterable>
          <el-option v-for="item in PRODUCT_TYPE" :key="item.value" :label="item.label" :value="item.value" />        
        </el-select> -->
        <el-input maxlength="60" v-trim clearable v-model="searchForm.contractNumber" style="width: 200px;"
          placeholder="请输入合同号" />
        <div class="as-gravity-center-start">
          <div class="date-label">日期:</div>
          <el-date-picker unlink-panels v-model="value1" type="datetimerange" range-separator="到"
            start-placeholder="统计开始日期" end-placeholder="统计结束日期" style="margin: 0 10px 10px 10px"
            format="YYYY-MM-DD HH:mm:ss" :clearable="false" @change="dateChangeHandle" />
        </div>
      </template> 
    </crud-template>
  </div>
</template>

<!-- 选装模式成本统计 -->
<script lang="ts" setup>
  // @ts-ignore crudFrom模板
  import CrudTemplate from "@/crud/index.vue";
  import {
    ref,
    onMounted,
    computed
  } from "vue";
  import { ElMessage } from "element-plus";
  import BaseService from "@/utils/baseService";
  import moment from "moment";
  import $storeinitData from "@/store/initData"; //引入tab vuex
  import { exportFn, getDefaultTime, importFn, reportExportFn } from '@/views/settlement/exportFn'
  import { IsPermission } from '@/router/routerUtil'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  const PRODUCT_TYPE = computed(() => {
    return $storeinitData.state.dictData['PRODUCT_TYPE'] || []
  })

  const crudRef = ref();
  const searchForm = ref({
    promotionChannels: "",
    productType: "",
    contractNumber: "",
    startTime: "",
    endTime: "",
    type: 1, // 1查询 2导出
  });
  const tableData = ref([]);

  //表单数据配置
  const formLabelWidth = "180px";
  const field = ref({
    tabSize: "small", //Table 的尺寸 large / default /small (默认default)
    searchShow: true, //是否显示搜索模块(默认false)
    border: true, //是否添加边框(默认false)
    dialogCustom: true, //自定义Dialog (默认false)
    dialogFooter: true, //隐藏弹窗页脚显示 (默认false)
    dialogWidth: "40%", //dialog宽度 (默认40%)
    crudShow: true, //是否显示CURD操作栏 (默认true)
    crudChildShow: true, //是否显示CURD子操作栏 (默认true)
    paginStart: true, //是否显示分页查询 (默认false)
    isPageSizes: true,
    pageLayout: 'total, sizes, prev, pager, next',
    titleDialog: "", //table 标题
    paging: {
      pageSize: 10,
      currentPage: 1,
      total: 0,
      costPriceAll: 0,
      costAmountAll: 0,
    },
    crud: {
      add: false,
      cudText: [
        {
          label: '成本单价总金额：',
          key: 'costPriceAll',
          isAmount: true,
        },
        {
          label: '成本总金额：',
          key: 'costAmountAll',
          isAmount: true,
        }
      ],
    },
    searchOperation: {
      isInitiateApproval: IsPermission(route, 'INITIATE_APPROVAL'), //发起审批
      initiateApprovalData: {
        key: 'optional_mode',
        processName: '选装模式成本统计',
        reqFileName: 'SETTLE_OPTIONAL_OPTIONALMODECOSTIMPORT'
      },
      isDownload: IsPermission(route, 'DERIVE_BASE'), // 导出
      isToLead: IsPermission(route, 'BATCH_LEAD'), // 导入
      isAdd: false,
      isTransferMachine: false,
      isTemplate: IsPermission(route, 'BATCH_LEAD'),
      templateUrl: import.meta.env.VITE_APP_UPLOAD_URL + 'sett-minio/template/收支管理/支出管理/选装模式成本统计(支出类).xlsx',
      templateFileName: '选装模式成本统计导入模板'
    },
    tableSize: -1,
    operateShow: true, //是否为表格添加操作栏(默认true)
    operateTitle: "操作", //操作栏标题(默认为"")
    operateFixed: false, //操作栏是否固定(默认false)
    operateWidth: "100", //操作栏宽度
    operate: {
      info: IsPermission(route, 'INFO_LIST'), //详情
      edit: false, //是否编辑(默认true)
      delete: false, //是否删除(默认true)
      remark: false, // 查看
    },
    extend: [
      {
        type: "index",
        label: "序号",
      },
    ],
    field: [
      {
        label: "推广渠道",
        prop: "promotionChannels",
        form: {
          formLabelWidth: formLabelWidth,
          width: "45%",
          type: "input",
        },
      },
      {
        label: "产品类型",
        prop: "productType",
        // listData: PRODUCT_TYPE,
        form: {
          formLabelWidth: formLabelWidth,
          width: "45%",
          type: "input",
          // listData: PRODUCT_TYPE,
        },
      },
      {
        label: "合同号",
        prop: "contractNumber",
        form: {
          formLabelWidth: formLabelWidth,
          width: "45%",
          type: "input",
        },
      },
      {
        label: "成本单价(元)",
        prop: "costPrice",
        isAmount: true,
        form: {
          formLabelWidth: formLabelWidth,
          width: "45%",
          type: "input",
        },
      },
      {
        label: "数量",
        prop: "quantity",
        form: {
          formLabelWidth: formLabelWidth,
          width: "45%",
          type: "input",
        },
      },
      {
        label: "成本金额(元)",
        prop: "costAmount",
        isAmount: true,
        form: {
          formLabelWidth: formLabelWidth,
          width: "45%",
          type: "input",
        },
      },
      {
        label: "日期",
        prop: "dateTime",
        funRuleStarts: true,
        funRule: (time: any) => {
          return time ? time.replace('T', ' ') : '-';
        },
        form: {
          funRuleStarts: true,
          funRule: (time: any) => {
            return time ? time.replace('T', ' ') : '-';
          },
          formLabelWidth: formLabelWidth,
          width: "45%",
          type: "input",
        },
      },
      {
        label: "备注",
        prop: "remark",
        form: {
          formLabelWidth: formLabelWidth,
          width: "45%",
          type: "input",
        },
      }
    ],
  });
  // 搜索按钮
  function btnSearch() {
    field.value.paging.currentPage = 1;
    getList();
  }
  // 搜索重置
  function refreshLeft() {
    field.value.paging.currentPage = 1;
    searchForm.value = {
      promotionChannels: "",
      productType: "",
      contractNumber: "",
      type: 1,
      startTime: "",
      endTime: "",
    };
    value1.value = defaultTime
    dateChangeHandle()
    tableData.value = [];
    getList();
  }

  const defaultTime: [Date, Date] = getDefaultTime('day', 1)
  const value1: any = ref(defaultTime) // 筛选时间
  // 时间
  function dateChangeHandle() {
    if (value1.value) {
      searchForm.value.startTime = value1.value[0]
      searchForm.value.endTime = value1.value[1]
    } else {
      searchForm.value.startTime = ''
      searchForm.value.endTime = ''
    }
  }
  function dateChange(time) {
    if (time) {
      time = moment(time).format("YYYY-MM-DDTHH:mm:ss");
    }
    return time
  }
  // 获取列表
  function getList() {
    if (!searchForm.value.startTime || !searchForm.value.endTime) {
      ElMessage.error('请选择查询开始时间和结束时间')
      return
    }
    searchForm.value.type = 1
    crudRef.value.tableLoding = true;
    // 参数
    const params: any = {
      pageNo: field.value.paging.currentPage,
      pageSize: field.value.paging.pageSize,
    };
    searchForm.value.startTime = dateChange(searchForm.value.startTime)
    searchForm.value.endTime = dateChange(searchForm.value.endTime)
    const searchFormList = { ...searchForm.value };
    for (const key in searchFormList) {
      if (searchFormList[key]) {
        params[key] = searchFormList[key];
      }
    }
    BaseService.postN('/settlew/optional/optionalmodecostfind', params).then((res: any) => {
      if (res && res.code === 0) {
        const bizContent = res.data
        const data = bizContent.data || [];
        tableData.value = data;
        crudRef.value.tableLoding = false;
        field.value.paging.total = bizContent.totalCount;
        field.value.paging.costPriceAll = bizContent.costPriceAll;
        field.value.paging.costAmountAll = bizContent.costAmountAll;
      } else {
        crudRef.value.tableLoding = false;
        ElMessage.error(res.message);
      }
    });
  }
  function handleCurrentChange(val: number) {
    field.value.paging.currentPage = val;
    getList();
  }
  // 生成报表
  function generateAeport() {
    downloadHandle(1)
  }
  // 导出
  const downloadHandle = (type) => {
    searchForm.value.type = 2
    searchForm.value.startTime = dateChange(searchForm.value.startTime)
    searchForm.value.endTime = dateChange(searchForm.value.endTime)
    if (type) {
      reportExportFn('/settlew/optional/optionalmodecostfind', searchForm.value, '选装模式成本统计').then((res) => {
        const initiateApprovalData = field.value.searchOperation.initiateApprovalData
        field.value.searchOperation.initiateApprovalData = { ...initiateApprovalData, ...res }
      }).finally(() => {
        console.log('error')
      })
    } else {
      // 普通导出
      exportFn('/settlew/optional/optionalmodecostfind', searchForm.value, '选装模式成本统计')
    }
  }
  // 导入
  function importData(url, reportFileName) {
    importFn('/settlew/optional/optionalmodecostimport', () => { }, { excelUrl: url, reportFileName })
  }
  onMounted(() => {
    dateChangeHandle()
    getList();
  })

</script>
