<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="generateStatementFlag"
    title="生成对账单"
    :append-to-body="true"
    :close-on-click-modal="false"
    :maxable="true"
    :resizable="true"
    width="65%"
    :before-close="cancel"
  >
    <div v-loading="loading">
      <el-form
        ref="form"
        :model="form"
        class="el-form-box"
        >
        <ele-pro-table
            ref="table"
            :needPage="false"
            :columns="columns"
            :datasource="form.datasource"
            row-key="id"
            @columns-change="handleColumnChange"
            :cache-key="cacheKeyUrl"
            height="350"
            full-height="calc(100vh - 76px)"
        > 
            <template v-slot:orderNo="scope">
                <el-form-item :prop="'datasource.' + scope.$index + '.orderNo'">
                    <el-input v-model="scope.row.orderNo" @click.native="openOrderDialog(scope.row, scope.$index)"></el-input>
                <!-- <el-select
                    v-model="scope.row.batchStockId" 
                    placeholder="请选择"
                    @change="batchNoChange(scope.$index, scope.row)"
                >
                    <el-option
                    v-for="item in scope.row.batchNoList || []"
                    :key="item.id"
                    :label="item.batchNo"
                    :value="item.id"
                    >
                    </el-option>
                </el-select> -->
                </el-form-item>
            </template>
        </ele-pro-table>
        </el-form>
    </div>
    <div slot="footer" class="footer">
      <el-button
        v-if="dialogType !== 'view'"
        type="primary"
        @click="save"
        v-loading="saveLoading"
        >生成
      </el-button>
      <el-button @click="cancel">返回</el-button>
    </div>
    <orderListDialog
      ref="orderListDialogRef"
      @changeParent="getOrderInfo"
    ></orderListDialog>
  </ele-modal>
</template>

<script>
  import InventoryTable from './inventoryTable.vue';
  import recorpayTableList from './recorpayTableList.vue';

  import saleForm from './saleForm.vue';
  import {
    getStatementRecordListAPI,
    infoAccountStatementAPI,
    createAccountStatementAPI,
    updateAccountStatementAPI,
    accountstatementInfoAPI
  } from '@/api/saleManage/accountstatement';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import OrderListDialog from './orderListDialog.vue';
  import tabMixins from '@/mixins/tableColumnsMixin';

  export default {
    name: 'GenerateStatement',
    mixins: [tabMixins],
    components: {
      processSubmitDialog,
      InventoryTable,
      saleForm,
      recorpayTableList,
      OrderListDialog
    },
    //客户管理数据
    props: {
      generateStatementFlag: {
        type: Boolean,
        default: false
      },
      contactData: {
        type: Object,
        default: () => {
          return {};
        }
      },
      saleOrderData: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },
    data() {
      return {
        fullscreen: false,
        loading: false,
        saveLoading: false,
        form: {
          datasource: []
        },
        datasource: [],
        dataForm: {
          sourceType: 1,
          dateType: 1,
          queryDimension: 2,
          dateValue: '',
          contactId: '',
          contactName: '',
          sourceName: '',
          sourceId: '',
          type: '',
          year: '',
          quarter: '',
          month: '',
          dateTimeRange: [],
          orderNo: '',
          orderId: '',
          id: '',
          startDate: '',
          endDate: '',
          repliedFiles: []
        },
        title: '',
        processSubmitDialogFlag: false,
        dialogType: '',
        columns: [
          {
            width: 60,
            label: '序号',
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            minWidth: 120,
            prop: 'name',
            label: '调拨名称',
            slot: 'name',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'allotCode',
            label: '调拨单号',
            slot: 'allotCode',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            minWidth: 140,
            prop: 'orderNo',
            label: '销售订单号',
            slot: 'orderNo',
            align: 'center',
            showOverflowTooltip: true
          }
        ]
      };
    },
    computed: {},
    methods: {
      open(dialogType, row) {
        this.dialogType = dialogType;
        console.log('row~~~', row);
        this.form.datasource = row || [];
      },
      //打开订单弹窗
      openOrderDialog(row, index) {
        let item = { id: row.orderId };
        this.$refs.orderListDialogRef.open(item, index);
      },
      //选择订单信息回调
      getOrderInfo(arr, index) {
        console.log('arr~~~', arr, index, this.form.datasource[index]);
        this.form.datasource[index].orderNo = arr.map(item => item.orderNo).join(',');
        // this.dataForm.sourceType = 3;
        // let params = Object.assign({}, this.dataForm, {
        //   orderId: obj.id,
        //   orderNo: obj.orderNo,
        //   contactId: obj.partaId,
        //   contactName: obj.partaName,
        //   sourceName: obj.orderNo,
        //   sourceId: obj.id
        // });
        // this.$emit('update:dataForm', params);
        // this.reloadTableData();
      },

      //关闭弹窗
      cancel() {
        this.$emit('update:generateStatementFlag', false);
      },
   
      //保存
      async save(is) {
        if (!this.form.datasource.length)
          return this.$message.warning('暂无对账信息');
        let api =
          this.dialogType == 'add'
            ? createAccountStatementAPI
            : updateAccountStatementAPI;
        let params = {
          ...this.dataForm,
          orderList: this.form.datasource,
        };
        console.log('params~~~', params);
        this.saveLoading = true;
        try {
          let data = await api(params);
          this.saveLoading = false;
          if (is == 'sub') {
            await this.submitApprove(data);
            return;
            // await submitAccountStatementApproveAPI({
            //   businessId: data,
            //   type: this.dataForm.type
            // });
          }
          this.$message.success('操作成功');
          this.reload();
        } catch (error) {
          this.saveLoading = false;
        }
        this.$message.success('操作成功');
        this.reload();
      },
      async submitApprove(res) {
        let data = await accountstatementInfoAPI(res);
        this.processSubmitDialogFlag = true;
        this.$nextTick(() => {
          let params = {
            businessId: res,
            businessKey: 'sales_account_statement_approve',
            formCreateUserId: data.createUserId,
            variables: {
              type: data.type,
              businessCode: data.statementNo,
              businessName: data.contactName,
              businessType: '对账单'
            }
            // callBackMethodType : '1',
            // callBackMethod : 'proTargetPlanApproveApiImpl.updatePlanApprovalStatus',
            // pcHandle : '/bpm/handleTask/components/project-manage/plan-manage/submit.vue',
            // pcView : '/bpm/handleTask/components/project-manage/plan-manage/detailDialog.vue',
            // miniHandle : '',
            // miniView : '',
          };
          this.$refs.processSubmitDialogRef.init(params);
        });
      },
      reload() {
        this.cancel();
        //刷新主页面
        this.$emit('done');
      }
    }
  };
</script>
<style scoped lang="scss">
  ::v-deep.el-divider {
    margin: 10px;
    font-weight: bold;
  }
  .el-form-item {
    margin-bottom: 0px;
  }
</style>
