<template>
    <a-modal
      title="选择销售订单(Select Sale Order)"
      width="95%"
      :visible="visible"
      :maskClosable="false"
      switchFullscreen
      @ok = "handleOk"
      @cancel="handleCancel">
        <div>
          <a-card  :body-style="{ padding: '10px' }" :bordered="false" style="margin: 10px;">
            <div class="table-page-search-wrapper">
                <a-form :model="queryParams"  @keyup.enter.native="searchQuery" :label-col="{ style: 'width: 200px' }">
                <a-row :gutter="24">
                    <a-col :md="6" :sm="8">
                        <a-form-item label="订单编号(bill code)">
                            <j-input placeholder="请输入" v-model:value="queryParams.billCode"></j-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="8">
                        <a-form-item label="单据日期(bill date)">
                            <a-range-picker value-format="YYYY-MM-DD"  v-model:value="billDate"  @change="changeBillDate" class="query-group-cust"/>
                        </a-form-item>
                    </a-col> 
                    <template v-if="toggleSearchStatus">
                        <a-col :md="6" :sm="8">
                            <a-form-item label="项目(project)">
                                <ApiSelect
                                    :api="ProjectOption"
                                    showSearch
                                    v-model:value="queryParams.project"
                                    optionFilterProp="label"
                                    resultField="records"
                                    labelField="code"
                                    valueField="id"
                                    :params='{pageSize:-1}'
                                    :disabled="fatherProject!==''"
                                    />
                            </a-form-item>
                        </a-col>
                        <a-col :md="6" :sm="8">
                            <a-form-item label="产品分类(production class)" >
                                <!-- <j-input placeholder="请输入" v-model:value="queryParams.classId"></j-input> -->
                                <ApiSelect
                                    :api="ClassList"
                                    showSearch
                                    v-model:value="queryParams.productionClass"
                                    optionFilterProp="label"
                                    resultField="records"
                                    labelField="name"
                                    valueField="id"
                                    :params='{pageSize:-1}'
                                    />
                            </a-form-item>
                        </a-col>
                        <a-col :md="6" :sm="8">
                            <a-form-item label="优先级(priority)" >
                                <JDictSelectTag v-model:value="queryParams.priority" placeholder="请选择" dictCode="priority"/>
                            </a-form-item>
                        </a-col>
                        <a-col :md="12" :sm="16" v-if="showCustomer=='no'">
                            <a-form-item label="供应商(supplier)" >
                                <JSelect   v-model:value="queryParams.supplierId" :get-option-url="supplierOption" :showField="showField"  :disabled="fatherSupplier!==''"></JSelect>
                            </a-form-item>
                        </a-col>
                        <a-col :md="12" :sm="16" v-if="showCustomer=='yes'">
                            <a-form-item label="客户(customer)">
                                <JSelect   v-model:value="queryParams.customer" :get-option-url="CustomerOption" :showField="showField"  @change="changeCustmer"></JSelect>
                            </a-form-item>
                        </a-col>
                        <a-col :md="6" :sm="8">
                            <a-form-item label="机型(model)">
                                <JDictSelectTag v-model:value="queryParams.headModel" placeholder="请选择" dictCode="model_typer" style="width: 100%;"/>
                            </a-form-item>
                        </a-col>
                        
                        <a-col :md="6" :sm="8">
                            <a-form-item label="产品英文名(English name)" >
                                <j-input placeholder="请输入" v-model:value="queryParams.englishName"></j-input>
                            </a-form-item>
                        </a-col>
                        <a-col :md="6" :sm="8">
                            <a-form-item label="产品编码(product code)">
                                <j-input placeholder="请输入" v-model:value="queryParams.productCode"></j-input>
                            </a-form-item>
                        </a-col>
                        <a-col :md="6" :sm="8">
                            <a-form-item label="型号(model)">
                                <j-input placeholder="请输入" v-model:value="queryParams.childModel"></j-input>
                            </a-form-item>
                        </a-col> 
                        
                        <a-col :md="6" :sm="8">
                            <a-form-item label="业务员(salesman)">
                                <j-input placeholder="请输入" v-model:value="queryParams.salesman"></j-input>
                            </a-form-item>
                        </a-col>   
                        <a-col :md="6" :sm="8">
                            <a-form-item label="销售部门(sale department)" > 
                                <j-input placeholder="请输入" v-model:value="queryParams.saleDepartment"></j-input>
                            </a-form-item>
                        </a-col>                      
                    </template>
                    <a-col :md="6" :sm="8">
                        <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                            <a-button type="primary" @click="searchQuery" >查询(search)</a-button>
                            <a-button type="primary" @click="searchReset"  style="margin-left: 8px">重置(reset)</a-button>
                            <a @click="handleToggleSearch" style="margin-left: 8px">
                            {{ toggleSearchStatus ? '收起' : '展开' }}
                            <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                            </a>
                        </span>
                    </a-col>
                </a-row>
            </a-form>
           </div>
        </a-card>

        <a-card  :body-style="{ padding: '10px' }" :bordered="false" style="margin: 10px;">
            <a-alert type="info" show-icon class="alert" style="margin-bottom: 8px">
            <template #message>
                <template v-if="selectedRowKeys.length > 0">
                <span>已选中 {{ selectedRowKeys.length }} 条记录</span>
                <a-divider type="vertical" />
                <a @click="selectedRowKeys = []">清空</a>
                </template>
                <template v-else>
                <span>未选中任何数据</span>
                </template>
            </template>
            </a-alert>
            <a-table
                :columns="columns"
                :row-key="record => record.childId"
                :data-source="dataSource"
                bordered
                size="small"
                @change="handleTableChange"
                :pagination="pagination"
                :scroll="{ x: 4000, y: 400 }"
                :rowSelection="{ onSelect: onSelect, onSelectAll: onSelectAll, selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            >
            </a-table>
        </a-card>
      </div>
    </a-modal>
</template>
<script lang="ts" setup>
    import {ref, reactive } from 'vue';
    import { defHttp} from '/@/utils/http/axios';
    import { message } from 'ant-design-vue';
    import { filterObj, getFileAccessHttpUrl } from '/@/utils/common/compUtils';
    import { JDictSelectTag,ApiSelect,JInput,JSelect} from '/@/components/Form';
    import {ProjectOption,ClassList,supplierOption} from '../saleCode/deliveryNotice/delivertNoticeForm.api';
    import {CustomerOption} from '../saleCode/saleContract/SaleContract.api';
    const emit = defineEmits([ 'selectSaleOrder']); //定义emit
    var showField = ref('currency_dictText+name');
    var visible = ref(false)
    var fatherProject = ref('')
    var fatherSourceCode = ref('')
    var fatherSupplier =ref('')
    var fatherType = ref('')
    var fatherCustomer=ref('')
    var showCustomer = ref('no')
    var getListUrl =ref('')
    var columns=[]
    var columns1 = [
        { 
            type: 'selection',
            fixed: 'left',
            width:0
        },
        {
            title: '订单编号(bill code)',
            dataIndex: 'billCode',
            key: 'billCode',
            align:"center",
            width:250,
            
        },
        {
            title: '单据日期(bill date)',
            dataIndex: 'billDate',
            key: 'billDate',
            align:"center"
        },
        {
            title: '项目(project)',
            dataIndex: 'projectName',
            key: 'projectName',
            align:"center",
            width:250,
            ellipsis: true,
        },
        {
            title: '供应商(supplier)',
            dataIndex: 'supplierName',
            key: 'supplierName',
            align:"center",
            ellipsis: true,
            ifShow:showCustomer.value=='no'?true:false,
            // className:showCustomer.value=='no'?'tableShow':'tableHiddle'
        },
        {
            title: '客户(customer)',
            dataIndex: 'customerName',
            key: 'customerName',
            align:"center",
            width:250,
            // ellipsis: true,
            // className:showCustomer.value=='yes'?'tableShow':'tableHiddl
        },
        {
            title: '优先级(priority)',
            dataIndex: 'priority_dictText',
            key: 'priority_dictText',
            align:"center"
        },
        {
            title: '产品分类(production class)',
            dataIndex: 'productionClass_dictText',
            key: 'productionClass_dictText',
            align:"center",
            width:250,
        },
        {
            title: '机型(model)',
            dataIndex: 'headModel',
            key: 'headModel',
            align:"center"
        },
        {
            title: '销售部门(sale department)',
            dataIndex: 'saleDepartment',
            key: 'saleDepartment',
            align:"center"
        },
        {
            title: '业务员(salesman)',
            dataIndex: 'salesman',
            key: 'salesman',
            align:"center"
        },
        {
            title: '产品编码(product code)',
            dataIndex: 'productCode',
            key: 'productCode',
            align:"center",
            width:250,
        },
        {
            title: '产品英文名(English name)',
            key: 'englishName',
            dataIndex: 'englishName',
            align:"center",
            width:250,
            ellipsis: true,
        },
        {
            title: '型号(childModel)',
            key: 'childModel',
            dataIndex: 'childModel',
            align:"center"
        },
        {
            title: '厂家(factory)',
            key: 'factory',
            dataIndex: 'factory',
            align:"center",
            width:250
        },
        {
            title: '质量等级(quantity grade)',
            key: 'quantityGrade',
            dataIndex: 'quantityGrade',
            align:"center",
            width:250,
        },
        {
            title: '数量(quantity)',
            key: 'quantity',
            dataIndex: 'quantity',
            align:"center",
            width:250,
        },
        // {
        //     title: '单价(price)',
        //     key: 'taxPrice',
        //     dataIndex: 'taxPrice',
        //     align:"center",
        //     width:250,
        // },
        // {
        //     title: '金额(tax money)',
        //     key: 'taxAmount',
        //     dataIndex: 'taxAmount',
        //     align:"center",
        //     width:250,
        // },
    ];
    const labelCol = ref({
    xs: { span: 24 },
    sm: { span: 9 },
    });
    const wrapperCol = ref({
        xs: { span: 24 },
        sm: { span: 15 },
    });
    const labelCol1 = ref({
    xs: { span: 24 },
    sm: { span: 12 },
    });
    const wrapperCol1 = ref({
        xs: { span: 24 },
        sm: { span: 12 },
    });
    const dataSource =ref([]);
    let selectedRowKeys = ref([]);
    let selectionRows = ref([]);
    const toggleSearchStatus = ref(false);
    var billDate = ref([])
    const queryParams = ref({
        billCode:'',
        project:'',
        projectName:'',
        productionClass:'',
        priority:'',
        supplierId:'',
        supplier:'',
        headModel:'',
        englishName:'',
        productCode:'',
        childModel:'',
        billDate_begin:'',
        billDate_end:'',
        saleDepartment:'',
        salesman:'',
        customer:'',
    });
    let pagination = ref({
      current: 1,
      pageSize: 10,
      total: '', // 假设总共有100条数据
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
      },
      size:'small'
    });
    function loadData(){
        let params = getQueryParams();
        defHttp.get({ url: getListUrl.value ,params}, { isTransformResponse: false })
        .then((res) => {
            if (res.success) {
                dataSource.value = res.result.records;
                pagination.value.total = res.result.total;
                pagination.value.current = res.result.current;
                pagination.value.pageSize = res.result.size;                
            } else {
                message.error(res.message);
            }
        })
        .finally(() => {
            // loading.value = false;
        });
    }
    function getQueryParams(){
        let params = Object.assign(queryParams.value);
        params.pageNo = pagination.value.current;
        params.pageSize = pagination.value.pageSize;
        if(fatherProject.value&&fatherProject.value!==''){
            queryParams.value.project = fatherProject.value
        }else {
            queryParams.value.project = params.project
        }
        if(fatherSupplier.value&&fatherSupplier.value!==''){
            queryParams.value.supplierId = fatherSupplier.value
        }else {
            queryParams.value.supplierId = params.supplierId
        }
        if(fatherCustomer.value&&fatherCustomer.value!==''){
            queryParams.value.customer = fatherCustomer.value
        }else {
            queryParams.value.customer = params.customer
        }
        return filterObj(params);
    }
    function handleTableChange(paginations, filters, sorter){
        pagination.value.total = paginations.total;
        pagination.value.current = paginations.current;
        pagination.value.pageSize = paginations.pageSize;
        loadData()
    }
    function searchQuery(){
        pagination.value.current = 1
        selectedRowKeys.value = []
        selectionRows.value=[]
        loadData();
    }
    function searchReset(){
        billDate.value = []
        queryParams.value = {
            billCode:'',
            project:'',
            projectName:'',
            productionClass:'',
            priority:'',
            supplierId:'',
            supplier:'',
            headModel:'',
            englishName:'',
            productCode:'',
            childModel:'',
            billDate_begin:'',
            billDate_end:'',
            saleDepartment:'',
            salesman:'',
            customer:'',
        }
        pagination.value.current =1;
        pagination.value.pageSize = 10; 
        selectedRowKeys.value = []
        selectionRows.value=[]
        loadData();
    }
    function handleToggleSearch(){
        toggleSearchStatus.value = !toggleSearchStatus.value;
    }
    function onSelectChange(selectedRowKeys1, selectionRows1) {
        var arr = []
        selectionRows.value.map(item=>{
            arr.push(item.childId)
        })
        selectedRowKeys.value =  arr
    }
    function onSelect(record, selected, selectionRows1, nativeEvent) {
        if (selected) {
            selectionRows.value.push(record)
            console.log( selectionRows.value);
        }else{
            const delIndex = selectionRows.value.findIndex((val) => {
            return val.childId === record.childId
            })
            selectionRows.value.splice(delIndex, 1)
        }
    }
    function onSelectAll(selected, selectionRows1, changeRows) {
        if (selected) {
            selectionRows.value = selectionRows.value.concat(changeRows)
        }
        if (!selected) {
            let selectionRows2 = JSON.parse(JSON.stringify(selectionRows.value))
            const delIndex = []
            selectionRows2.forEach((item, index) => {
            changeRows.forEach((val, itemIndex) => {
                if (item.childId === val.childId) {
                delIndex.push(index)
                }
            })
            })
            delIndex.forEach((item) => {
            delete selectionRows2[item]
            })
            selectionRows2 = selectionRows2.filter((item) => {
                return item !== undefined
            })
            selectionRows.value = selectionRows2
        }
    }
    function handleOk(){
        if(fatherType.value=='payRequest'){
            emit('selectSaleOrder', selectionRows.value)
            handleCancel()
        }else if(fatherType.value=='purOrder'){
            var 
            arrSupplier=[],
            arrProject=[]
            selectionRows.value.map(item=>{
                arrSupplier.push(item.supplierId)
                arrProject.push(item.project)
            })
            if(fatherSupplier.value&&fatherSupplier.value!==''){
                arrSupplier.push(fatherSupplier.value)
            }
            if(fatherProject.value&&fatherProject.value!==''){
                arrProject.push(fatherProject.value)
            }
            if(selectedRowKeys.value.length==0){
                message.error('请勾选数据');
            }else if(new Set(arrSupplier).size!==1){
                message.error('请勾选供应商相同的数据');
            }else if(new Set(arrProject).size!==1){
                message.error('请勾选项目相同的数据');
            }else{
                emit('selectSaleOrder', selectionRows.value)
                handleCancel()
            }

        }else{
            var arr = [],
            arrSupplier=[]
            selectionRows.value.map(item=>{
                arr.push(item.billCode)
                arrSupplier.push(item.supplierId)
            })
            if(fatherSourceCode.value&&fatherSourceCode.value!==''){
                arr.push(fatherSourceCode.value)
            }
            if(selectedRowKeys.value.length==0){
                message.error('请勾选数据');
            }else if(new Set(arr).size!==1){
                message.error('请勾选订单编号相同的数据');
            }else if(new Set(arrSupplier).size!==1){
                message.error('请勾选供应商相同的数据');
            }else{
                emit('selectSaleOrder', selectionRows.value)
                handleCancel()
            }
        }
        
    }
    function handleCancel(){
        visible.value = false
        selectedRowKeys.value = []
        selectionRows.value=[]
        billDate.value = []
        queryParams.value = {
            billCode:'',
            project:'',
            projectName:'',
            productionClass:'',
            priority:'',
            supplierId:'',
            supplier:'',
            headModel:'',
            englishName:'',
            productCode:'',
            childModel:'',
            billDate_begin:'',
            billDate_end:'',
            saleDepartment:'',
            salesman:'',
            customer:'',
        }
        pagination.value.current =1;
        pagination.value.pageSize = 10; 
    }
    function getTable(formData,data){
        visible.value = true
        if(formData.projectName&&formData.projectName!==''){
            fatherProject.value = formData.project
        }else{
            fatherProject.value = ''
        }
        // getListUrl.value ='/saleCode/saleOrder/selectSaleOrderDetailAlert'
        //发货通知单里使用不显示供应商
        if(data=='delivery'){
            if(formData.sourceCode&&formData.sourceCode!==''){
                fatherSourceCode.value = formData.sourceCode2
            }else{
                fatherSourceCode.value = ''
            }
            fatherType.value='other'
            showCustomer.value = 'yes'
            getListUrl.value ='/saleCode/saleOrder/selectSaleOrderDetailAlertDelivery'
            columns= columns1.filter(function(value, i) {
                return i !== 4;
            });
            if(formData.customer&&formData.customer!==''){            
                fatherCustomer.value = formData.customer
            }else{
                fatherCustomer.value = ''
            }
        }else  if(data=='purOrder'){       
            fatherType.value='purOrder'                 
            showCustomer.value = 'no'
            columns= columns1.filter(function(value, i) {
                return i !== 5;
            });
            if(formData.supplierName&&formData.supplierName!==''){
                fatherSupplier.value = formData.supplier
            }else{
                fatherSupplier.value = ''
            }
            getListUrl.value ='/saleCode/saleOrder/selectSaleOrderDetailAlertExistSup'
        }
        loadData()
    }
    function getTableFromSalePayRequestForm(){
        visible.value = true
        fatherProject.value = ''
        fatherSourceCode.value = ''
        fatherType.value='payRequest'
        showCustomer.value = 'no'
        columns= columns1.filter(function(value, i) {
            return i !== 4;
        });
        getListUrl.value ='/saleCode/saleOrder/selectSaleOrderDetailAlert'
        loadData()
    }

    function changeBillDate(prop){
       if(prop){
            billDate.value = prop
            queryParams.value.billDate_begin = prop[0]
            queryParams.value.billDate_end = prop[1]
       }else{
            billDate.value = []
            queryParams.value.billDate_begin = ''
            queryParams.value.billDate_end = ''
       }
       
    }
    function changeCustmer(value){
        queryParams.value.customer = queryParams.value.customer
        fatherCustomer.value=''
    }
    defineExpose({
      getTable,
      getTableFromSalePayRequestForm
    });
</script>
<style scoped lang="less">
/deep/.ant-form-item{
    margin-bottom: 8px !important;
}
// /deep/.ant-table-wrapper .ant-table-thead > tr > th, .ant-table-wrapper .ant-table-thead > tr > td{
//     padding: 8px !important;
// }
/deep/.tableHiddle {
  display: none;
}
/deep/.tableShow{
  display: revert;
}
</style>