<template>
  <div class="app-container">
    <!--工具栏-->
    <!-- 搜索 -->
    <div v-if="crud.props.searchToggle">
      <!-- 搜索 -->
      <!--      <label class="el-form-item-label">单号</label>-->
      <el-input v-model="query.code" clearable placeholder="单号" style="width: 185px;" class="filter-item"
                @keyup.enter.native="crud.toQuery"/>
      <el-input v-model="query.cusCode" clearable placeholder="箱单号" style="width: 185px;" class="filter-item"
                @keyup.enter.native="crud.toQuery"/>
      <el-input v-model="query.relatedBill1" clearable placeholder="发票号" style="width: 185px;" class="filter-item"
                @keyup.enter.native="crud.toQuery"/>
      <AreaSelect v-model="query.areaCode" :value-key="'id'" :bexb=false placeholder="请选择库区" style="width: 150px;" class="filter-item" @change="getChangeAreaValue"/>

      <!--      <el-input v-model="query.orderDate" clearable placeholder="订单日期" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />-->
      <!--      <label class="el-form-item-label">状态</label>-->
      <el-select v-model="query.status" clearable placeholder="状态" value-key="id" class="filter-item"
                 @keyup.enter.native="crud.toQuery">
        <el-option
          style="width: 180px"
          v-for="item in this.dict.asn_status"
          :key="item.id"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <rrOperation :crud="crud"/>
    </div>
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <!--      <el-button-->
      <!--        slot="right"-->
      <!--        class="filter-item"-->
      <!--        type="primary"-->
      <!--        icon="el-icon-plus"-->
      <!--        size="mini"-->
      <!--        @click="inserAsnOnOffM()"-->
      <!--      >-->
      <!--        新增-->
      <!--      </el-button>-->
      <crudOperation :permission="permission" :tableKey="this.$options.name">
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          v-permission="permission.inserAsn"
          @click="inserAsnOnOffM()"
        >
          新增
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          size="mini"
          :disabled="mutilPutawayVisible"
          v-permission="permission.inserAsn"
          @click="showMutilPutawayBtn(crud.selections)">
          批量上架
        </el-button>

        <el-button
          slot="left"
          class="filter-item"
          type="success"
          icon="el-icon-upload2"
          size="mini"
          v-permission="permission.inserAsn"
          @click="showImportDialog">
          导入
        </el-button>

        <!--        <el-button-->
        <!--          slot="right"-->
        <!--          class="filter-item"-->
        <!--          type="primary"-->
        <!--          icon="el-icon-plus"-->
        <!--          size="mini"-->
        <!--          :disabled="crud.selections.length!=1"-->
        <!--          @click="asnDetailRouter(crud.selections)"-->
        <!--        >-->
        <!--          明细-->
        <!--        </el-button>-->
      </crudOperation>

      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                 :title="crud.status.title" width="400px" :height="crud.tableHeight" border
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="单号" prop="code">
            <el-input :disabled="true" v-model="form.code" style="width: 200px;"/>
          </el-form-item>
          <el-form-item label="箱单号" prop="code">
            <el-input v-model="form.cusCode" style="width: 200px;"/>
          </el-form-item>
          <el-form-item label="发票号" prop="relatedBill1">
            <el-input v-model="form.relatedBill1" style="width: 200px;"/>
          </el-form-item>
          <el-form-item label="订单日期" prop="orderDate">
            <el-input v-model="form.orderDate" style="width: 200px;"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.description" style="width: 200px;"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--   批量上架   -->
      <el-dialog title="批量上架" :visible.sync="mutilPutawayVisible" width="500px">
        <el-form ref="plsjForm" :model="plsjForm" label-width="80px">
          <!--<el-form-item label="库位" prop="pointId" :rules="[{ required: true, message: '库位不能为空'}]">
            <el-select v-model="plsjForm.pointId" value-key="id" placeholder="请选择库位" style="width: 250px">
              <el-option
                  v-for="(item,index) in pointOptions"
                  :key="item.id+''+item.code"
                  :label="item.code"
                  :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>-->

          <el-form-item label="库位" prop="point"  :rules=" { required: true, message: '库位不能为空', trigger: 'blur' }">
            <PointSelect v-model="plsjForm.point" :value-key="'id'" :point_type="'CH'" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="mutilPutawayVisible = false">取 消</el-button>
          <el-button type="primary" @click="mutilPutawayBtn(crud.selections)">确认</el-button>
        </div>
      </el-dialog>

      <!-- 导入对话框 -->
      <el-dialog :visible.sync="importDialogVisible" title="导入" width="800px">
        <el-tabs v-model="activeImportTab" type="card">
          <el-tab-pane label="模板一：标准导入" name="template1">
            <div class="import-content">
             <!-- <div class="template-info">
                <h4>模板说明：</h4>
                <p>适用于<span style="color: red">标准</span>导入，包含INVOICE NO.、BOI、PO&LN NO.、PART
                  NO.、DESCRIPTION、Q'TY(PCS) 、C/NO.</p>
                <el-button type="primary" size="small" @click="downloadTemplate('template1')">下载模板</el-button>
              </div>-->
              <el-upload
                class="upload-demo"
                drag
                accept=".xlsx,.xls,.csv"
                action="#"
                :auto-upload="false"
                :file-list="fileList1"
                :on-change="handleExcelChange"
                :on-remove="handleExcelRemove"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip" style="color: red">注意：更新文件后请重新上传(支持.xlsx, .xls,
                  .csv 格式文件)
                </div>
              </el-upload>
            </div>
          </el-tab-pane>

          <el-tab-pane label="模板二：大物导入" name="template2">
            <div class="import-content">
              <!--   <div class="template-info">
                  <h4>模板说明：</h4>
                  <p>适用于<span style="color: red">大物</span>导入，包含INVOICE NO.、BOI、PO&LN NO.、PART
                    NO.、DESCRIPTION、Q'TY(PCS) 、C/NO.</p>
                </div>-->
                <el-upload
                  class="upload-demo"
                  drag
                  accept=".xlsx,.xls,.csv"
                  action="#"
                  :auto-upload="false"
                  :file-list="fileList2"
                  :before-upload="beforeExcelUpload"
                  :on-change="handleExcelChange"
                  :on-remove="handleExcelRemove"
                >
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <div class="el-upload__tip" slot="tip" style="color: red">注意：更新文件后请重新上传(支持.xlsx, .xls,
                    .csv 格式文件)
                  </div>
                </el-upload>
              </div>
            </el-tab-pane>

            <el-tab-pane label="模板三：空运发票箱单导入" name="template3">
              <div class="import-content">
                <!--  <div class="template-info">
                   <h4>模板说明：</h4>
                   <p>适用于<span style="color: red">空运发票箱单</span>导入，包含INV.NO.、A-PROS CASE NO、KMT NO. PO&LN NO.、PART NO.、
                     DESCRIPTION、Q'TY 、C/NO.</p>
                 </div>-->
                 <el-upload
                   class="upload-demo"
                   drag
                   accept=".xlsx,.xls,.csv"
                   action="#"
                   :auto-upload="false"
                   :file-list="fileList3"
                   :before-upload="beforeExcelUpload"
                   :on-change="handleExcelChange"
                   :on-remove="handleExcelRemove"
                 >
                   <i class="el-icon-upload"></i>
                   <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                   <div class="el-upload__tip" slot="tip" style="color: red">注意：更新文件后请重新上传(支持.xlsx, .xls,
                     .csv 格式文件)
                   </div>
                 </el-upload>
               </div>
             </el-tab-pane>
           </el-tabs>

           <div slot="footer" class="dialog-footer">
             <el-button @click="cancelImport">取消</el-button>
             <el-button type="primary" @click="confirmImport" :loading="importLoading">确认导入</el-button>
           </div>
         </el-dialog>
         <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
                @selection-change="crud.selectionChangeHandler" :height="crud.tableHeight" @select="invVerifySTFM"
                @select-all="invVerifySTFAll" border
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="序号" width="80px" align="center"/>
        <el-table-column prop="code" label="单号" align="center"/>
        <el-table-column prop="cusCode" label="箱单号"  align="center"/>
        <el-table-column prop="relatedBill1" label="发票号" align="center"/>
        <el-table-column prop="billType.name" label="单据类型"/>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            {{ dict.label.asn_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column prop="orderDate" label="订单日期" width="140px" align="center"/>
        <el-table-column prop="receivedDate" label="收货日期" width="140px" align="center"/>
        <el-table-column prop="orderQuantity" label="订单数量" align="center"/>
        <el-table-column prop="receivedQuantity" label="收货数量" align="center"/>
        <el-table-column prop="area.name" label="库区" align="center"/>
        <el-table-column prop="createBy" label="创建人" align="center"/>
        <el-table-column prop="createTime" label="创建时间" width="140px" align="center"/>
        <el-table-column v-if="checkPer(['admin','asn:del'])" label="操作" width="175px" align="center"
                         fixed="right">
          <template slot-scope="scope">
            <el-button
              class="filter-item"
              type="primary"
              size="mini"
              style="float: right"
              @click="asnDetailRouter(scope.row)"
            >
              明细
            </el-button>
            <udOperation
              :data="scope.row"
              :permission="permission"
            >
            </udOperation>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <div style="float: right;">
        <pagination/>
      </div>
    </div>
  </div>
</template>

<script>
import DateRangePicker from "@/components/DateRangePicker/index.vue";
import crudAsn, {getCodeNo, queryAsnAll, save,mutilPutawaySys} from '@/api/asn'
import importData from '@/api/importData'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import rrOperation from '@crud/RR.operation.vue'
import crudOperation from '@crud/CRUD.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import pagination from '@crud/Pagination.vue'
import {getAreas} from '@/api/area'
import {getBillType} from '@/api/billType'
import {add, queryAsnDetailAll} from '@/api/asnDetail'
import {queryPointList} from '@/api/point'
import {queryItemAll} from '@/api/item'
import {formatDate} from '@/utils/commonUtils'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import {cancelReceiv} from "@/api/xppRecord";
import BomAccountPointSelect from "@/views/generic-component/BomAccountPointSelect.vue";
import PointSelect from "@/views/generic-component/PointSelect.vue";
import AreaSelect from "@/views/generic-component/AreaSelect.vue";

const defaultForm = {
  id: null,
  code: null,
  area: null,
  status: 'OPEN',
  cusCode: null,
  relatedBill1: null,
  relatedBill2: null,
  relatedBill3: null,
  orderDate: null,
  estimateDate: null,
  receivedDate: null,
  fromName: null,
  fromAddress: null,
  fromMan: null,
  fromTel: null,
  orderQuantity: 0,
  receivedQuantity: 0,
  putawayQuantity: 0,
  vehicle: null,
  billType: null,
  dept: null,
  description: null,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null
}
export default {
  name: 'Asn',
  components: {
    AreaSelect,
    PointSelect,
    BomAccountPointSelect,
    pagination, crudOperation, rrOperation, udOperation, DateRangePicker, UploadExcelComponent},
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['asn_status'],
  cruds() {
    return CRUD({
      title: 'asn', url: 'api/asn', idField: 'id', sort: 'id,desc', crudMethod: {...crudAsn}, optShow: {
        add: false,
        edit: false,
        del: true,
        reset: false,
        download: false
      },
      query: { billTypeCode: 'XDRK'},
      queryOnPresenterCreated: true
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'asn:add'],
        edit: ['admin', 'asn:edit'],
        del: ['admin', 'asn:del'],
        invVerify: ['admin', 'asn:invVerify'],
        inserAsn: ['admin', 'asn:inserAsn'],
        import: ['admin', 'asn:import'],
        mutilPutaway:['admin', 'asn:mutilPutaway']
      },
      rules: {
        code: [
          {required: true, message: '单号不能为空', trigger: 'blur'}
        ],
        area: [
          {required: true, message: '库区不能为空', trigger: 'blur'}
        ],
        orderDate: [
          {required: true, message: '订单日期不能为空', trigger: 'blur'}
        ]
      },
      queryTypeOptions: [
        {key: 'code', display_name: '单号'},
        {key: 'areaCode', display_name: '库区'},
        {key: 'status', display_name: '状态查询'},
      ],
      areaOptions: [],
      pointOptions: [],
      billTypeOptions: [],
      //新增数据的弹窗开关
      inserAsnOnOff: false,
      updateAsnOnOff: false,
      asnFrom: {
        id: null,
        code: null,
        area: null,
        status: 'OPEN',
        cusCode: null,
        relatedBill1: null,
        relatedBill2: null,
        relatedBill3: null,
        orderDate: null,
        estimateDate: null,
        receivedDate: null,
        fromName: null,
        fromAddress: null,
        fromMan: null,
        fromTel: null,
        orderQuantity: 0,
        receivedQuantity: 0,
        putawayQuantity: 0,
        vehicle: null,
        billType: null,
        dept: null,
        description: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null
      },
      asnDetailFrom: {
        id: null,
        asn: null,
        item: null,
        stock: null,
        lineNo: null,
        po: null,
        status: 'OPEN',
        point: null,
        orderQty: 0,
        receivedQty: 0,
        moveQty: 0,
        putQty: 0,
        weight: 0,
        volume: 0,
        remark: null,
        propC1: null,
        propC2: null,
        propC3: null,
        propC4: null,
        propC5: null,
        propC6: null,
        propD1: null,
        propD2: null,
        deptId: null,
        sourceName: null,
        sourceId: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null
      },
      asnDetailList: [],
      itemListData: [],
      asnOptions: [],
      invVerifySTF: true,
      mutilPutawayVisible:false,
      selectIds: {
        ids: []
      },
      plsjForm:{ids: [],pointId: null},
      // 导入相关数据
      importDialogVisible: false,
      activeImportTab: 'template1',
      importLoading: false,
      fileList1: [],  // 用于存储当前文件
      fileList2: [],
      fileList3: []
    }
  },
  mounted() {
    //数据加载
    // this.getAreaOptionsAll()
    // this.getBillTypeAll()
    // this.getAsnDetailAll()
    // this.itemDataGet()
    // this.getPointData()
    // this.getAsnData()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    getAreaOptionsAll() {
      getAreas().then(res => {
        this.areaOptions = res
      })
    },
    getBillTypeAll() {
      getBillType().then(res => {
        this.billTypeOptions = res
      })
    },
    getAsnDetailAll() {
      let obj = {}
      queryAsnDetailAll(obj).then(res => {
        this.asnDetailList = res
      })
    },
    //新增加的开关
    inserAsnOnOffM(data) {
      this.$router.push({path: '/business-asn/viewAsnDetail'})
    },
    submitFrom(data) {
      crudAsn.add(data).then(res => {
        this.$message.success('新增成功')
        this.inserAsnOnOff = false
        this.asnFrom = defaultForm;
        this.crud.toQuery()
      })
    },
    billTypeSelect(value) {
      this.inserAsnOnOffM(value.code)
    },
    //物料数据
    itemDataGet() {
      queryItemAll({}).then(res => {
        this.itemListData = res
      }).catch(e => {
        this.$message({
          showClose: true,
          message: '物料加载失败',
          type: 'error'
        })
      })
    },

    asnDetailRouter(datas) {
      this.$router.push({path: '/business-asn/viewAsnDetail', query: {ids: datas.id}})
    },
    invVerifySTFM(selection, row) {
      if (selection.length > 0) {
        this.invVerifySTF = false;
      } else {
        return
      }
      //判断
      for (const selectionElement of selection) {
        //打开/收货中
        if (!(selectionElement.status === 'OPEN' || selectionElement.status === 'RECEIVING')) {
          this.invVerifySTF = true;
        }
      }
    },
    invVerifySTFAll(selection) {
      if (selection.length > 0) {
        this.invVerifySTF = false;
      } else {
        return
      }
      //判断
      for (const selectionElement of selection) {
        //打开/收货中
        if (!(selectionElement.status === 'OPEN' || selectionElement.status === 'RECEIVING')) {
          this.invVerifySTF = true;
        }
      }
    },
    //批量上架-弹出页面
    showMutilPutawayBtn(data) {
      this.mutilPutawayVisible = true
      this.queryPointList()
    },
    queryPointList() {
      queryPointList({"type":"CH"}).then(res => {
        this.pointOptions = res
      })
    },
//批量上架
    mutilPutawayBtn(data) {
      let data_ = this.plsjForm;
      data_.ids = data.map(v => v.id);
      data_.pointId=this.plsjForm.point.id;
      console.log(data_)
      console.log(this.plsjForm)
      mutilPutawaySys(data_).then(res=>{
        this.crud.toQuery()
        this.$message.success(res)
        this.mutilPutawayVisible = false
      })
    },
    getChangeValue(dben) {
      this.plsjForm.pointId = dben.id;
    },
    getChangeAreaValue(dben) {
      this.query.areaCode = dben.code;
    },


    // 导入相关方法
    showImportDialog() {
      this.importDialogVisible = true
    },

    downloadTemplate(templateType) {
      const templateConfig = {
        template1: {
          filename: '标准导入模板.xlsx',
          headers: ['INVOICE NO.', 'BOI', 'PO&LN NO.', 'PART NO.', 'DESCRIPTION', 'Q\'TY ', 'C/NO.'],
          sampleData: [
            ['KCWT04108SM', 'EXP -', '7291-5366', 'RD829-6640-7', 'ASSY BRACKET,SWING', '3', '7074786'],
            ['KCWT04108SM', 'EXP -', '7291-5366', 'RD829-6640-7', 'ASSY BRACKET,SWING', '3', '7074785']
          ]
        }
      }
      const config = templateConfig[templateType]
      if (!config) {
        this.$message.error('模板类型不存在')
        return
      }

      // 创建Excel文件并下载
      this.createAndDownloadExcel(config)
    },

    createAndDownloadExcel(config) {
      // 这里需要引入XLSX库来创建Excel文件
      // 由于项目可能没有XLSX，我们使用简单的CSV格式
      let csvContent = '\uFEFF' // BOM for UTF-8
      csvContent += config.headers.join(',') + '\n'

      config.sampleData.forEach(row => {
        csvContent += row.join(',') + '\n'
      })

      const blob = new Blob([csvContent], {type: 'text/csv;charset=utf-8;'})
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', config.filename.replace('.xlsx', '.csv'))
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    async confirmImport() {
      // 提取当前 tab 对应的文件信息
      const getFileFromTab = (tab) => {
        const fileMap = {
          template1: this.fileList1,
          template2: this.fileList2,
          template3: this.fileList3,
        };
        const list = fileMap[tab] || [];
        return list.length > 0 ? list[0] : null;
      };

      const currentFile = getFileFromTab(this.activeImportTab);
      if (!currentFile || !currentFile.raw) {
        this.crud.notify('请先上传文件', CRUD.NOTIFICATION_TYPE.WARNING);
        return;
      }

      const fileName = currentFile.name;
      this.importLoading = true;
      console.log(`开始导入 ${this.activeImportTab} 文件: ${fileName}`);

      const formData = new FormData();
      formData.append('file', currentFile.raw);
      formData.append('templateType', this.activeImportTab);

      try {
        const response = await importData.importAsnData(formData);
        console.log(response);
        if (response.status === 200) {
          this.crud.notify(response.message, CRUD.NOTIFICATION_TYPE.SUCCESS);
          this.importDialogVisible = false;
          this.crud.toQuery(); // 刷新列表

          // 动态清空 fileList
          ['fileList1', 'fileList2', 'fileList3'].forEach(key => {
            this[key] = [];
          });
        }
      } catch (error) {
        console.error('导入失败:', error);
      } finally {
        this.importLoading = false;
      }
    },
    cancelImport() {
      this.fileList1 = [];
      this.fileList2 = [];
      this.fileList3 = [];
      this.importDialogVisible = false
    },
    // el-upload专用：校验文件大小和类型
    beforeExcelUpload(file) {
      const isExcel = /\.(xlsx|xls|csv)$/.test(file.name)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isExcel) {
        this.crud.notify('只支持.xlsx, .xls, .csv 格式文件', CRUD.NOTIFICATION_TYPE.ERROR);
        return false
      }
      if (!isLt2M) {
        this.crud.notify('文件大小不能超过2MB', CRUD.NOTIFICATION_TYPE.ERROR);
        return false
      }
      return false
    },
    // el-upload专用：文件列表改变时；显示最新的文件
    handleExcelChange(file, fileList) {
      this.beforeExcelUpload(file)
      // 只保留当前tab的文件，其它tab清空
      if (this.activeImportTab === 'template1') {
        this.fileList1 = [file];
        this.fileList2 = [];
        this.fileList3 = [];
      } else if (this.activeImportTab === 'template2') {
        this.fileList1 = [];
        this.fileList2 = [file];
        this.fileList3 = [];
      } else if (this.activeImportTab === 'template3') {
        this.fileList1 = [];
        this.fileList2 = [];
        this.fileList3 = [file];
      }
    },
    // el-upload专用：文件移除
    handleExcelRemove() {
      if (this.activeImportTab === 'template1') {
        this.fileList1 = [];
      } else if (this.activeImportTab === 'template2') {
        this.fileList2 = [];
      } else if (this.activeImportTab === 'template3') {
        this.fileList3 = [];
      }
    },
  }
}
</script>

<style scoped>
.import-content {
  padding: 5px 0;
}

.template-info {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.template-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.template-info p {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}

</style>
