<template>
  <!-- 装箱单-面料列表 -->
  <div id="fabricList">
    <!-- 查询 -->
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">

             <a-col :md="6" :sm="8">
              <a-form-item label="单据号">
                <a-input placeholder="请输入单据号" v-model="queryParam.documentNo"></a-input>
              </a-form-item>
            </a-col>

            <!-- <a-col :md="6" :sm="8">
              <a-form-item label="订单号">
                <a-input placeholder="请输入订单号" v-model="queryParam.orderNumber"></a-input>
              </a-form-item>
            </a-col> -->

            <a-col :md="6" :sm="8">
              <a-form-item label="集装箱号">
                <a-input placeholder="请输入集装箱号" v-model="queryParam.containerNumber"></a-input>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
              <a-form-item label="外销发票号">
                <a-input placeholder="请输入外销发票号" v-model="queryParam.exportInvoiceNo"></a-input>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</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 :bordered="false" style="marginTop:10px;">
      <div class="table-operator">
        <a-button type="primary" @click="addFabric" icon="plus">新增</a-button>
        <a-button type="primary" @click="bitchSubmitList" icon="check">批量提交</a-button>
        <a-button type="primary" @click="bitchCancelSubmitList" icon="close">批量取消提交</a-button>
        <a-button type="primary" @click="push" icon="export">推送</a-button>
        <a-button type="primary" icon="download" @click="handleExportXls('装箱单-面辅料')">导出</a-button>
      </div>

      <!-- 子表  :scroll="{ x: 1500 }" 内容少 无需滚动-->
      <a-table
        bordered
        :columns="fabricListColumns"
        :data-source="fabricListData"
        :loading="loading"
        :scroll="{ x: 1500 , y: 500 }"
        :pagination="pagination"
        :row-key="record => record.id"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <!-- 集装箱号 输入框
        <a-form-model
          slot="containerNo"
          slot-scope="text, record"
          :ref="record.index"
          :model="record"
          style="width:100%;height:40px"
        >
          <a-form-model-item prop="containerNo">
            <a-input style="width:100%" v-model="record.containerNumber" />
          </a-form-model-item>
        </a-form-model> -->
         <!-- 单据状态 -->
        <span slot="state" slot-scope="text, record">
          <a-tag color="orange" v-if="record.status == '0'">已保存</a-tag>
          <a-tag color="green" v-if="record.status == '1'">已提交</a-tag>
        </span>

        <!-- 操作 -->
        <span slot="operationSlot" slot-scope="text, record">
          <a @click="accessoryUpload(record)" style="color:green;">附件上传</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多<a-icon type="down"/></a>
            <a-menu slot="overlay" v-if="record.status=='0'">
              <a-menu-item><a @click="details(record)">详情</a></a-menu-item>
              <a-menu-item><a @click="edit(record)">编辑</a></a-menu-item>
              <a-menu-item><a @click="itemXls(record)">导出</a></a-menu-item>
              <!-- <a-menu-item><a @click="submit(record)">提交</a></a-menu-item> -->
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" ok-text="是" cancel-text="否" @confirm="handleDelete(record.id)">
                  <a href="javascript:void(0);" style="color:red;">删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
            <!-- 已提交 -->
            <a-menu slot="overlay" v-if="record.status=='1'">
              <a-menu-item><a @click="details(record)">详情</a></a-menu-item>
              <a-menu-item><a @click="itemXls(record)">导出</a></a-menu-item>
              <!-- <a-menu-item><a @click="cancel(record)">取消提交</a></a-menu-item> -->
            </a-menu>
              
          </a-dropdown>
        </span>
      </a-table>
    </a-card>

    <!-- 抽屉 -->
    <div>
      <addFabric-drawer ref="addFabricDrawer" :father="aa" @ok="modalFormOk" :fatherList="getFabricList"></addFabric-drawer>
      <detailsFabric-drawer ref="detailsFabricDrawer" :father="bb" @ok="modalFormOk"></detailsFabric-drawer>
      <editFabric-drawer ref="editFabricDrawer" :father="cc" @ok="modalFormOk"></editFabric-drawer>
    </div>
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { downFile } from '@/api/manage'
import JEllipsis from '@/components/jeecg/JEllipsis'
import moment from 'moment'
import addFabricDrawer from '@views/packing-list/packinglist-fabrics/addFabricDrawer.vue'
import detailsFabricDrawer from '@views/packing-list/packinglist-fabrics/detailsFabricDrawer.vue'
import editFabricDrawer from '@views/packing-list/packinglist-fabrics/editFabricDrawer.vue'
import { fabricList,fabricListId,deleteFabricList,submitList,cancelSubmit,bitchSubmit,bitchCancelSubmit} from '@api/document/packing-list/packinglist-fabrics'

export default {
  name: 'FabricList', // 装箱单-面料
  mixins: [JeecgListMixin],
  components: { JEllipsis, moment, addFabricDrawer, detailsFabricDrawer, editFabricDrawer },

  data() {
    // let ellipsis = (v, l = 20) => <j-ellipsis value={v} length={l} />
    return {
      // 表头
      fabricListColumns: [
        {
          title: '单据号',
          dataIndex: 'documentNo',
          width: 160,
          ellipsis: true,
          className: 'replacecolor'
        },
        // {
        //   title: '订单号',
        //   dataIndex: 'orderNumber',
        //   width: 160,
        //   className: 'replacecolor'
        // },
         {
          title: '集装箱号',
          dataIndex: 'containerNumber',
          width: 120,
           ellipsis: true,
          // scopedSlots: { customRender: 'containerNo' },
          className: 'replacecolor'
        },

        //  {
        //   title: '发票号',
        //   dataIndex: 'invoiceNo',
        //   width: 160,
        //    ellipsis: true,
        //   className: 'replacecolor'
        // },
        {
          title: '外销发票号',
          dataIndex: 'exportInvoiceNo',
          width: 150,
           ellipsis: true,
          className: 'replacecolor'
        },
       
        {
          title: '装柜日期',
          dataIndex: 'latestDateOfShipment',
          width: 120,
           ellipsis: true,
          className: 'replacecolor'
        },
        {
          title: '成衣工厂',
          dataIndex: 'garmentFactory',
          width: 140,
           ellipsis: true,
          className: 'replacecolor'
        },
       

        {
          title: '制单人',
          dataIndex: 'createBy',
          width: 120,
           ellipsis: true,
          className: 'replacecolor'
        },
        {
          title: '制单日期',
          dataIndex: 'preparedDate',
          width: 140,
           ellipsis: true,
          // 有问题，自动显示当日日期
          // customRender: text => {
          //   return moment(text).format('YYYY-MM-DD')
          // },
          className: 'replacecolor'
        },
        {
          title: '托书号',
          dataIndex: 'shippingOrderNumber',
          width: 160,
           ellipsis: true,
          className: 'replacecolor'
        },
         {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'state' },
          width: 140,
          className: 'replacecolor'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operationSlot' },
          width: 150,
          // fixed: 'right',
          className: 'replacecolor'
        }
      ],

      fabricListData: [],

      selectedRowKeys: [], // 勾选航
      loading: false, // 表格加载

      // 查询条件
      queryParam: {
        pageNo: '' // 初始页
      },
      pagination:{},
      url: {
        // syncUser: '/act/process/extActProcess/doSyncUser',
        list: '/sys/user/list',
        // delete: '/sys/user/delete',
        // deleteBatch: '/sys/user/deleteBatch',
        exportXlsUrl: '/sys/user/exportXls', // 导出
        importExcelUrl: 'sys/user/importExcel' // 导入
      }
    }
  },
  created() {
    this.getFabricList()
  },
  methods: {
    //分页查询
    getFabricList(){
       this.$nextTick(() => {
         this.queryParam.pageSize = 20
        fabricList(this.queryParam).then(res => {
          if (res.success) {
            this.fabricListData = res.result.records;
            this.pagination = {
              total: res.result.total,
              current: res.result.current,
              pageSize: res.result.size
            }
          }else{
              this.$message.error(res.message);
          }
        })
      })
    },
    // 查询按钮
    searchQuery() {
      this.toggleSearchStatus = false
      this.queryParam.pageNo = ''
      this.getFabricList()
    },

    //重置查询
    searchReset() {
      this.queryParam = {}
      this.getFabricList()
    },
    // ------------------------------------
    // 推送
    push() {},
    // 新增
    addFabric() {
      console.log('新增-装箱单面料')
      this.$refs.addFabricDrawer.visible = true
    },
    // --------------------------------------
    // 操作 附件上传
    accessoryUpload() {},

     // 列表导出
    handleExportXls(fileName) {
      downFile('/splfi/syPackingListFabric/exportXls').then(data => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      })
    },

    // 操作 单条数据导出
    itemXls(record) {
       downFile('/splfi/syPackingListFabric/exportXls',{id:record.id}).then(data => {
         if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
         if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), item + '.xlsx')
        }else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '装箱单' + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
       })
    },

    // 操作 详情
    details(record) {
      console.log('详情', record.id)
      // console.log('编辑')
       this.$nextTick(() => {
        fabricListId({id:record.id}).then(res => {
          if (res.success) {
            var data = res.result
             this.$refs.detailsFabricDrawer.visible = true
             this.$refs.detailsFabricDrawer.addFabric ={
               documentNo:data.documentNo,
              //  orderNumber:data.orderNumber,
               containerNumber:data.containerNumber,
               latestDateOfShipment:data.latestDateOfShipment,
               garmentFactory:data.garmentFactory,
               invoiceNo:data.invoiceNo,
               preparedBy:data.preparedBy,
               preparedDate:data.preparedDate,
               exportInvoiceNo:data.exportInvoiceNo,
               shippingOrderNumber:data.shippingOrderNumber,
               remarks:data.remarks,
               plumbumNo:data.plumbumNo,

             }
             if(record.documentNo.substr(0, 2) == "FL"){  
                this.$refs.detailsFabricDrawer.judageCloumn()
             }
             data.syPackingListFabricItem.map(item =>{
               if(item.manualYarnFlag == 0){
                 item.manualYarnFlag = '否'
               }else {
                 item.manualYarnFlag = '是'
               }
             })
              this.$refs.detailsFabricDrawer.addFabricData = data.syPackingListFabricItem
          }else{
              this.$message.error(res.message);
          }
        })
      })
    },
    // 操作 编辑
    edit(record) {
      // console.log('编辑')
       this.$nextTick(() => {
        fabricListId({id:record.id}).then(res => {
          if (res.success) {
            var data = res.result
             this.$refs.addFabricDrawer.visible = true
             this.$refs.addFabricDrawer.defaultMethod = 'edit'
             this.$refs.addFabricDrawer.addFabric ={
               id:data.id,
              //  orderNumber:data.orderNumber,
               documentNo:data.documentNo,
               containerNumber:data.containerNumber,
               latestDateOfShipment:data.latestDateOfShipment,
               garmentFactory:data.garmentFactory,
               invoiceNo:data.invoiceNo,
               preparedBy:data.preparedBy,
               preparedDate:data.preparedDate,
               exportInvoiceNo:data.exportInvoiceNo,
               shippingOrderNumber:data.shippingOrderNumber,
               remarks:data.remarks,
                plumbumNo:data.plumbumNo,
             }
             if(record.documentNo.substr(0, 2) == "FL"){  
                this.$refs.addFabricDrawer.judageCloumn()
             }
             data.syPackingListFabricItem.map(item =>{
                if(item.manualYarnFlag == 0){
                  this.$refs.addFabricDrawer.manualYarnDisabled = true
                  this.$forceUpdate()
               }else {
                 this.$refs.addFabricDrawer.manualYarnDisabled = false
                }            
               })
              this.$refs.addFabricDrawer.addFabricData = data.syPackingListFabricItem
              
               
          }else{
              this.$message.error(res.message);
          }
        })
      })
      
    },
    
    //提交
    submit(record){
      console.log(record.id)
      submitList({id:record.id}).then(res =>{
        if (res.success) {
           record.status = 1
           this.getFabricList()
            this.$message.success('提交成功')
          }else{
            this.$message.error(res.message);
          }
     })
    },

    cancel(record){
      console.log(record.id)
      cancelSubmit({id:record.id}).then(res =>{
        if (res.success) {
           record.status = 0
           this.getFabricList()
            this.$message.success('取消提交成功')
          }else{
            this.$message.error(res.message);
          }
     })
    },

    //批量提交
    bitchSubmitList(){
      for(var i =0;i<this.selectedRows.length;i++){
            var tickRow = this.selectedRows[i]
            if(tickRow.status === '1'){
               this.$message.error("部分数据是已提交，请勿重复提交！");
                return
             }
       }
      var ids = this.selectedRowKeys.toString()
       bitchSubmit({ids : ids}).then(res =>{
        if (res.success) {
            this.getFabricList()
            this.selectedRowKeys = []
            this.$message.success('提交成功');
          }else{
            this.$message.error(res.message);
          }
     })
    },

    //批量取消推送
    bitchCancelSubmitList(){
        for(var i =0;i<this.selectedRows.length;i++){
            var tickRow = this.selectedRows[i]
            if(tickRow.status === '0'){
               this.$message.error("含未提交数据，请重新选择！");
                return
             }
       }
      var ids = this.selectedRowKeys.toString()
       bitchCancelSubmit({ids : ids}).then(res =>{
        if (res.success) {
            this.getFabricList()
            this.selectedRowKeys = []
            this.$message.success('取消提交成功');
          }else{
            this.$message.error(res.message);
          }
     })

    },
    // 操作 删除
    handleDelete(id) {
       this.$nextTick(() => {
         if(this.queryParam.pageNo > 1 && this.fabricListData.length === 1){
          this.queryParam.pageNo = this.queryParam.pageNo -1
        }
        deleteFabricList({ id: id }).then(res => {
          if (res.success) {
            this.getFabricList()
            this.$message.success('删除成功')
          } else {
            this.$message.error('删除成功')
          }
       
        })
      })
    },
    // --------------------------------------
    // ??
    modalFormOk() {},
    // 选中行
    onSelectChange(keys, rows) {
      this.selectedRowKeys = keys
      this.selectedRows = rows
    },
    // --------------------------------------
    aa() {},
    bb() {},
    cc() {},
    // 分页、排序、筛选变化时触发
    handleTableChange(pagination, filters, sorter) {
      // console.log('当前页信息>>>>',pagination)
      this.queryParam.pageNo = pagination.current
      this.getFabricList()
    }
  },
  computed: {
    // 选中项
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
        },
        getCheckboxProps: record => ({
          props: {
            disabled: record.title === 'Disabled User',
            // Column configuration not to be checked
            title: record.title
          }
        })
      }
    }
  },
  mounted() {}
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
@import '~@assets/less/overwriter.less';
/deep/ .ant-table-thead > tr > th {
  text-align: center;
  // font-weight: 700;
}

/deep/ .ant-table-tbody {
  text-align: center;
}

// /deep/ th.replacecolor {
//   background-color: #ccc;
// }
</style>
