<template>
  <div class="edit-down-table">
    <vxe-pulldown class="edit-down-pulldown" ref="xDown" transfer>
      <template>
        <vxe-input
          class="edit-down-input"
          suffix-icon="fa fa-caret-down"
          v-model="row[column.property]"
          @click="clickEvent"
          @keyup="keyupEvent"
          @suffix-click="suffixClick"
        ></vxe-input>
      </template>
      <template #dropdown>
        <div class="edit-down-wrapper">
          <vxe-grid
            auto-resize
            border
            column-key
            height="auto"
            highlight-hover-row
            ref="vxeDialogTable"
            resizable
            row-id="uuid"
            show-header-overflow
            :columns="tableColumn"
            :data="tableData"
            :highlight-current-row="true"
            :loading="loading"
            :pager-config="tablePage"
            @cell-click="selectEvent"
            @page-change="pageChangeEvent"
          >
          </vxe-grid>
        </div>
      </template>
    </vxe-pulldown>
  </div>
</template>

<script>
import { getUserInfo } from '../../../lib/auth';
import {
  MaterialService,
  ElsOrgInfoService,
  SupplierMasterDataService,
  ElsAccountService,
  CostCenterRelationService,
  PriceRecordService,
  PurchaseDeliveryNoteService,
  VoucherNumberService,
  SaleDeliveryNoteService,
  ReconNumberService
} from '../../../lib/api/materials';
import { dialogTableColumn } from './const/dialogTableColumn';
import vxePopList from '../../../lib/vxe-popList';
import { ft } from '../../../lib/utils.js';

const LABELS = {
  failedToQueryData: ft('i18n_common_failed_to_query_specified_data', '查询?数据失败')
};

export default {
  name: 'EditDownTable',
  props: {
    listParams: {
      type: Object,
      default: () => {
        return {};
      }
    },
    listApi: {
      type: Object,
      default: () => {
        return {};
      }
    },
    params: Object,
    popupColumn: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      api: null,
      param: {},
      actionPath: '',
      tableColumn: [],
      row: null,
      column: null,
      loading: false,
      tableData: [],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      }
    };
  },
  created() {
    this.userInfo = getUserInfo();
    this.load();
    this.getData();
  },
  methods: {
    clickEvent() {
      this.$refs.xDown.showPanel();
    },

    getData(data) {
      this.loading = true;
      const params = this.param;
      params.currentPage = this.tablePage.currentPage;
      params.pageSize = this.tablePage.pageSize;
      Object.assign(params, data);

      const api = this.api;
      const curApi = this.actionPath ? api(this.actionPath, params) : api(params);

      curApi
        .then((res) => {
          this.loading = false;

          if (res.data && res.data.code === '200' && res.data.data) {
            const pageData = res.data.data;
            this.tableData = pageData.rows || [];
            this.tablePage.total = pageData.total;
          } else {
            console.log('Failed to list data.', res.data || res);
            this.$message.error(res.data.message || LABELS.failedToQueryData.replace('?', ''));
          }
        })
        .catch((err) => {
          this.loading = false;
          console.log('Error to list data.', err);
          this.$message.error(LABELS.failedToQueryData.replace('?', ''));
        });
    },

    async keyupEvent() {
      const { row, column } = this;
      const cellValue = row[column.property];
      const params = {};
      params[column.property] = cellValue;
      const res = await this.getData(params);
      const data = res.data.data.rows;
      if (cellValue) {
        this.tableData = data.filter((item) => item.field.indexOf(cellValue) > -1);
      } else {
        this.tableData = data;
      }
    },

    load() {
      const { row, column } = this.params;
      this.row = row;
      this.column = column;
      const prop = column.property;
      const list = vxePopList.filter((item) => {
        return item.prop === prop;
      });

      if (list.length > 0) {
        // 有预置的弹窗项
        switch (prop) {
          case 'materialNumber':
            this.tableColumn = this.popupColumn?.materialNumber || dialogTableColumn.material;
            this.api = this.listApi?.materialNumber || MaterialService.list;
            this.param = this.listParams?.materialNumber || {
              auditStatus: 0,
              elsAccount: this.userInfo.elsAccount,
              elsSubAccount: 1001,
              pageSize: this.tablePage.pageSize,
              currentPage: this.tablePage.currentPage,
              isFreeze: 'N',
              deleteIndicator: 'N'
            };
            break;
          //  物料组
          case 'materialGroup':
            this.tableColumn = this.popupColumn?.materialGroup || dialogTableColumn.materialGroup;
            this.api = this.listApi?.materialGroup || ElsOrgInfoService.listPurchaseOrganization;
            this.param = this.listParams?.materialGroup || {};
            this.actionPath = 'findPageList';
            break;
          //  采购组
          case 'purchaseGroup':
            this.tableColumn = this.popupColumn?.purchaseGroup || dialogTableColumn.purchaseGroup;
            this.api = this.listApi?.purchaseGroup || ElsOrgInfoService.listPurchaseGroup;
            this.param = this.listParams?.purchaseGroup || {};
            this.actionPath = 'findPageList';
            break;
          //  采购组织
          case 'purchaseOrganization':
            this.tableColumn =
              this.popupColumn?.purchaseOrganization || dialogTableColumn.purchaseOrganization;
            this.api =
              this.listApi?.purchaseOrganization || ElsOrgInfoService.listPurchaseOrganization;
            this.param = this.listParams?.purchaseOrganization || {};
            this.actionPath = 'findPageList';
            break;
          //  公司
          case 'companyCode':
            this.tableColumn = this.popupColumn?.companyCode || dialogTableColumn.companyCode;
            this.api = this.listApi.companyCode || ElsOrgInfoService.listPurchaseCompany;
            this.param = this.listParams?.companyCode || {};
            this.actionPath = 'findPageList';
            break;
          //  工厂
          case 'factory' || 'purchaseFactory':
            this.tableColumn =
              this.popupColumn?.factory ||
              this.popupColumn?.purchaseFactory ||
              dialogTableColumn.factory;
            this.api =
              this.listApi?.factory ||
              this.listApi?.purchaseFactory ||
              ElsOrgInfoService.listPurchaseFactory;
            this.param = this.listParams?.factory || this.listParams?.purchaseFactory || {};
            this.actionPath = 'findPageList';
            break;
          // 组织
          case 'orgId':
            this.tableColumn = this.popupColumn?.orgId || dialogTableColumn.orgId;
            this.api = this.listApi?.orgId || ElsOrgInfoService.listPurchaseFactory;
            this.param = this.listParams?.orgId || {};
            this.actionPath = 'findPageList';
            break;
          // 部门
          case 'applyDept':
            this.tableColumn = this.popupColumn?.applyDept || dialogTableColumn.department;
            this.api = this.listApi?.applyDept || ElsOrgInfoService.listPurchaseDeptartment;
            this.param = this.listParams?.applyDept || {};
            this.actionPath = 'findPageList';
            break;
          //  供应商
          case 'toElsAccount':
            this.tableColumn = this.popupColumn?.toElsAccount || dialogTableColumn.toElsAccount;
            this.api = this.listApi?.toElsAccount || SupplierMasterDataService.list;
            this.param = this.listParams?.toElsAccount || {};
            break;
          // 期望供应商
          case 'expectSupplierEls':
            this.tableColumn =
              this.popupColumn?.expectSupplierEls || dialogTableColumn.expectSupplierEls;
            this.api = this.listApi?.expectSupplierEls || SupplierMasterDataService.list;
            this.param = this.listParams?.expectSupplierEls || {};
            break;
          // 外协供应商
          case 'outSaleElsAccount':
            this.tableColumn =
              this.popupColumn?.outSaleElsAccount || dialogTableColumn.outSaleElsAccount;
            this.api = this.listApi?.outSaleElsAccount || SupplierMasterDataService.list;
            this.param = this.listParams?.outSaleElsAccount || {};
            break;
          // 收货供应商
          case 'deliverySupplierNumber':
            this.tableColumn =
              this.popupColumn?.deliverySupplierNumber || dialogTableColumn.deliverySupplierNumber;
            this.api = this.listApi?.deliverySupplierNumber || SupplierMasterDataService.list;
            this.param = this.listParams?.deliverySupplierNumber || {};
            break;
          // 成本中心
          case 'costCenter':
            this.tableColumn = this.popupColumn?.costCenter || dialogTableColumn.costCenter;
            this.api = this.listApi?.costCenter || CostCenterRelationService.list;
            this.param = this.listParams?.costCenter || {};
            this.actionPath = 'findPageList';
            break;
          // 采购计划员
          case 'purchasePlaner':
            this.tableColumn = this.popupColumn?.purchasePlaner || dialogTableColumn.purchasePlaner;
            this.api = this.listApi?.purchasePlaner || ElsAccountService.listEmployee;
            this.param = this.listParams?.purchasePlaner || {};
            break;
          // 采购负责人
          case 'purchasePerson':
            this.tableColumn = this.popupColumn?.purchasePerson || dialogTableColumn.purchasePerson;
            this.api =
              this.listApi?.purchasePerson || this.userInfo.station === 'sale'
                ? ElsAccountService.listPurchaseEmployeeBySale
                : ElsAccountService.listEmployee;
            this.param = this.listParams?.purchasePerson || {};
            if (this.userInfo.station === 'sale') {
              Object.assign(this.param, {
                toElsAccount: this.userInfo.elsSubaccountInfoDTO.toElsAccount
              });
            } else {
              Object.assign(this.param, { elsAccount: this.userInfo.elsAccount });
            }
            break;
          //  收货人
          case 'receivedUser':
            this.tableColumn = this.popupColumn?.receivedUser || dialogTableColumn.receivedUser;
            this.api = this.listApi?.receivedUser || ElsAccountService.listEmployee;
            this.param = this.listParams?.receivedUser || {};
            break;
          // 价格信息记录号
          case 'priceRecordNumber':
            this.tableColumn =
              this.popupColumn?.priceRecordNumber || dialogTableColumn.priceRecordNumber;
            this.api = this.listApi?.priceRecordNumber || PriceRecordService.list;
            this.param = this.listParams?.priceRecordNumber || {};
            break;
          // 选订单
          case 'orderNumber':
            this.tableColumn = this.popupColumn?.orderNumber || dialogTableColumn.orderNumber;
            this.api = this.listApi?.orderNumber || PurchaseDeliveryNoteService.list;
            this.param = this.listParams?.orderNumber || {};
            break;
          // 收货单
          case 'voucherNumber':
            this.tableColumn = this.popupColumn?.voucherNumber || dialogTableColumn.voucherNumber;
            this.api = this.listApi?.voucherNumber || VoucherNumberService.list;
            this.param = this.listParams?.voucherNumber || {};
            break;
          // 送货通知单
          case 'deliveryNoteNumber':
            this.tableColumn =
              this.popupColumn?.deliveryNoteNumber || dialogTableColumn.deliveryNoteNumber;
            this.api = this.listApi?.deliveryNoteNumber || SaleDeliveryNoteService.list;
            this.param = this.listParams?.deliveryNoteNumber || {};
            break;
          // 对账单
          case 'reconNumber':
            this.tableColumn = this.popupColumn?.reconNumber || dialogTableColumn.reconNumber;
            this.api = this.listApi?.reconNumber || ReconNumberService.list;
            this.param = this.listParams?.reconNumber || {};
            break;
        }
      } else {
        // 自定义的弹窗, 需要三个参数
        this.tableColumn = this.popupColumn[prop];
        this.api = this.listApi[prop];
        this.param = this.listParams[prop];
      }
    },

    async pageChangeEvent({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage;
      this.tablePage.pageSize = pageSize;
      await this.getData();
    },

    selectEvent(params) {
      const { row, column } = this;
      console.log(this);
      delete row.uuid;
      // row[column.property] = params.row[column.property];
      // Object.assign(row, params.row);
      vxePopList.forEach((item) => {
        if (item.prop === column.property) {
          const option = item.option;
          const dataValue = params.data[params.rowIndex][option.dataValueProp];
          const dataName = params.data[params.rowIndex][option.dataNameProp];
          if (typeof dataValue !== 'undefined' && typeof row[option.valueProp] !== 'undefined') {
            row[option.valueProp] = dataValue;
          }

          if (typeof dataName !== 'undefined') {
            const nameProp = option.nameProp;
            row[option.nameProp] = dataName;

            if (nameProp && typeof row[nameProp] !== 'undefined') {
              row[nameProp] = dataName;
            } else {
              const aliasProps = option.aliasProps || [];
              for (const aliasProp of aliasProps) {
                if (typeof row[aliasProp] !== 'undefined') {
                  row[aliasProp] = dataName;
                  break;
                }
              }
            }
          }
        }
      });
      /*
        params.data为弹窗表格的数据
        params.rowIndex为弹窗表格选中的第几行
        { row, column }: 当前表格的行数据和操作的列
       */
      this.$emit('selectDone', { row, column }, params.data[params.rowIndex]);
      this.$refs.xDown.hidePanel();
    },

    suffixClick() {
      this.$refs.xDown.togglePanel();
    }
  }
};
</script>

<style lang="scss" scoped>
.edit-down-pulldown {
  width: 100%;
}
.edit-down-wrapper {
  width: 800px;
  height: 500px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
}
</style>
