<template>

  <!-- 发运明细 列表 -->
  <div id="ShipmentList">
    <!-- 查询 回显 且 可编辑 -->
    <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-range-picker
                  style="width: 100%"
                  v-model="queryParam.timeRange"
                  format="YYYY-MM-DD"
                  :placeholder="['开始时间', '结束时间']"
                  @change="onDateChange"
                  @ok="onDateOk"
                />
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
              <a-form-item label="预发货日期">
                <a-date-picker
                  placeholder="请选择预发货日期"
                  format="YYYY-MM-DD"
                  style="width: 100%"
                  v-model="queryParam.preDeliveryDate"
                  @change="deliveryDateChange"
                />
              </a-form-item>
            </a-col>

            <template v-if="toggleSearchStatus">
              <a-col :md="6" :sm="8">
                <a-form-item label="业务员">
                  <a-input placeholder="请输入业务员" v-model="queryParam.salesman"></a-input>
                </a-form-item>
              </a-col>

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

              <a-col :md="6" :sm="8">
                <a-form-item label="是否被参照">
                  <a-select v-model="queryParam.refer">
                    <a-select-option value="">请选择</a-select-option>
                    <a-select-option value="0">否</a-select-option>
                    <a-select-option value="1">是</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :md="6" :sm="8">
                <a-form-model-item label="类型">
                  <a-select v-model="queryParam.flourOrGarment">
                    <a-select-option value="">请选择</a-select-option>
                    <a-select-option value="1">成衣</a-select-option>
                    <a-select-option value="0">面辅料</a-select-option>
                  </a-select>
                </a-form-model-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" 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.stop="addShipDet" icon="plus">新增</a-button>

        <a-button type="primary" icon="download" @click="handleExportXls('发运明细')">导出</a-button>
      </div>

      <!-- 子表  :row-key="record => record.id"  :pagination="ipagination-->
      <a-table
        v-if="shipmentListData"
        bordered
        rowKey="randomId"
        :columns="shipmentListColumns"
        :data-source="shipmentListData"
        :loading="loading"
        :pagination="pagination"
        :scroll="{ x: 1500 }"
        @change="handleTableChange"
      >
        <!-- 推送状态 -->
        <span slot="pushState" slot-scope="text, record">
          <a-tag color="#2db7f5" v-if="record.pushState == '0'">未推送</a-tag>
          <a-tag color="#87d068" v-if="record.pushState == '1'">推送成功</a-tag>
          <a-tag color="#f50" v-if="record.pushState == '2'">推送失败</a-tag>
        </span>

        <!-- 单据状态 -->
        <span slot="state" slot-scope="text, record">
          <a-tag color="orange" v-if="record.state == '0'">已保存</a-tag>
          <a-tag color="green" v-if="record.state == '1'">已提交</a-tag>
        </span>

        <!-- 操作 默认按钮  未提交未推送-->
        <span slot="operationSlot" slot-scope="text, record">
          <a href="javascript:void(0);" @click="declareElements(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.state == '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 href="javascript:void(0);" @click="itemNumberElement(record)">维护款号成分</a>
              </a-menu-item>

              <a-menu-item>
                <a-popconfirm title="确定提交吗?" ok-text="是" cancel-text="否" @confirm="submit(record)">
                  <a href="javascript:void(0);" style="color:green;">提交</a>
                </a-popconfirm>
              </a-menu-item>

              <a-menu-item>
                <a-popconfirm  arrowPointAtCenter title="确定删除吗?" ok-text="是" cancel-text="否" @confirm="handleDelete(record)">
                  <a href="javascript:void(0);" style="color:red;">删除</a>
                </a-popconfirm>
              </a-menu-item>

              <!-- <a-menu-item>
                <a href="javascript:void(0);" @click="itemNumberElement(record)">维护款号成分</a>
              </a-menu-item> -->
            </a-menu>

            <!-- 已提交 且 推送成功   -->
            <a-menu slot="overlay" v-if="record.pushState == '1' && record.state == '1'">
              <a-menu-item>
                <a @click="details(record)">详情</a>
              </a-menu-item>
            </a-menu>

            <!-- 已提交 且 推送失败  -->
            <a-menu slot="overlay" v-if="record.pushState == '2' && record.state == '1'">
              <a-menu-item>
                <a @click="details(record)">详情</a>
              </a-menu-item>

              <a-menu-item>
                <a-popconfirm title="确定重新推送吗?" ok-text="是" cancel-text="否" @confirm="rePush(record)">
                  <a href="javascript:void(0);" style="color:green;">重新推送</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>

            <!-- 已提交 -->
            <a-menu slot="overlay" v-if="record.state == '1'">
              <a-menu-item>
                <a @click="details(record)">详情</a>
              </a-menu-item>

              <a-menu-item>
                <a-popconfirm title="确定取消提交吗?" ok-text="是" cancel-text="否" @confirm="cancelSubmit(record)">
                  <a href="javascript:void(0);" style="color:red;">取消提交</a>
                </a-popconfirm>
              </a-menu-item>

              <a-menu-item>
                <a-popconfirm title="确定推送吗?" ok-text="是" cancel-text="否" @confirm="push(record)">
                  <a href="javascript:void(0);" style="color:green;">推送</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>

            <!-- 未推送 -->
            <a-menu slot="overlay" v-if="record.pushState == '0'">
              <a-menu-item>
                <a @click="details(record)">详情</a>
              </a-menu-item>

              <a-menu-item>
                <a-popconfirm title="确定推送吗?" ok-text="是" cancel-text="否" @confirm="push(record)">
                  <a href="javascript:void(0);" style="color:green;">推送</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </a-card>

    <!-- 抽屉  -->
    <div>
      <addShipDet-drawer ref="addShipDetDrawer" :fatherList="getShipmentList" @ok="modalFormOk" @close="closeAdd"></addShipDet-drawer>

      <editShipDet-drawer ref="editShipDetDrawer" :fatherList="getShipmentList" @ok="modalFormOk"></editShipDet-drawer>

      <detailsShipDet-drawer ref="detailsShipDetDrawer" @ok="modalFormOk"></detailsShipDet-drawer>
      <!-- 申报要素 弹框 -->
      <declareElements-modal ref="declareElementsModal"></declareElements-modal>

      <!-- 维护款号成分 -->
      <itemNumEle-modal ref="itemNumEleModal" :fatherList="getShipmentList"></itemNumEle-modal>
    </div>
  </div>

</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JEllipsis from '@/components/jeecg/JEllipsis'
import moment from 'moment'

import { downFile } from '@/api/manage'

import addShipDetDrawer from '@views/shipment-details/addShipDetDrawer.vue'
import detailsShipDetDrawer from '@views/shipment-details/detailsShipDetDrawer.vue'
import editShipDetDrawer from '@views/shipment-details/editShipDetDrawer.vue'
import declareElementsModal from '@views/shipment-details/declareElementsModal.vue'
import itemNumEleModal from '@views/shipment-details/itemNumEleModal.vue'
import { randomUUID } from '@/utils/util'

import {
  shipmentList,
  deleteShipment,
  submitShipment,
  shipmentQueryById,
  queryByDetails,
  queryDeclarationElements,
  cancelSubmitShipment,
  pushShipment,
  rePushShipment
} from '@api/document/shipmentList'

export default {
  name: 'ShipmentList', // 发运明细列表
  mixins: [JeecgListMixin],
  components: {
    JEllipsis,
    moment,
    addShipDetDrawer,
    detailsShipDetDrawer,
    editShipDetDrawer,
    declareElementsModal,
    cancelSubmitShipment,
    pushShipment,
    rePushShipment,
    itemNumEleModal
  },

  data() {
    let ellipsis = (v, l = 20) => <j-ellipsis value={v} length={l} />
    return {
      loading: false, // 表格加载
      id: '',
      shipmentListColumns: [
        {
          title: '单据号',
          dataIndex: 'documentNo',
          fixed: 'left',
          align: 'left',
          width: 140,
          className: 'replacecolor'
        },
        {
          title: '销售订单号',
          dataIndex: 'orderNumber',
          fixed: 'left',
          width: 150,
          className: 'replacecolor'
        },

        {
          title: '客户简称',
          dataIndex: 'customerAbbreviation',
          width: 220,
          align: 'left',
          className: 'replacecolor'
        },
        {
          title: '部门',
          dataIndex: 'salesDepartment',
          width: 120,
          className: 'replacecolor'
        },
        {
          title: '业务员',
          dataIndex: 'salesman',
          width: 120,
          className: 'replacecolor'
        },
        {
          title: '小po',
          dataIndex: 'smallPo',
          width: 120,
          className: 'replacecolor'
        },

        {
          title: 'pack id',
          dataIndex: 'packId',
          width: 120,
          className: 'replacecolor'
        },
        {
          title: '分销点',
          dataIndex: 'distributionPoint',
          width: 120,
          className: 'replacecolor'
        },
        {
          title: '款号',
          dataIndex: 'itemNumber',
          width: 180,
          className: 'replacecolor'
        },
        {
          title: '物料成分',
          dataIndex: 'materialComposition',
          width: 180,
          className: 'replacecolor',
          customRender: t => ellipsis(t),
        },
        {
          title: '预发货日期',
          dataIndex: 'preDeliveryDate',
          width: 120,
          customRender: text => {
            if (text == "" || text == null)
              return "";
            return moment(text).format('YYYY-MM-DD')
          },
          className: 'replacecolor'
        },
        {
          title: '预完工日期',
          dataIndex: 'preCompletionDate',
          width: 120,
          customRender: text => {
            if (text == "" || text == null)
              return "";
            return moment(text).format('YYYY-MM-DD')
          },
          className: 'replacecolor'
        },

        {
          title: '存货名称',
          dataIndex: 'inventoryName',
          width: 240,
          className: 'replacecolor',
          customRender: t => ellipsis(t),
        },
        {
          title: '英文品名',
          dataIndex: 'englishProductName',
          width: 120,
          className: 'replacecolor',
          customRender: t => ellipsis(t),
        },
        {
          title: '单价（销售）',
          dataIndex: 'salesUnitPrice',
          width: 120,
          className: 'replacecolor',
          
        },

        {
          title: '采购/委外订单号',
          dataIndex: 'purOrSubOrder',
          width: 180,
          className: 'replacecolor'
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          width: 120,
          className: 'replacecolor'
        },
        {
          // (采购/委外单价）
          title: '工厂单价',
          dataIndex: 'factoryUnitPrice',
          width: 120,
          className: 'replacecolor'
        },
        // {
        //   title: '申报要素(单证维护)',
        //   dataIndex: 'declarationElements',
        //   width: 120,
        //   className: 'replacecolor'
        // },
        {
          // （存货自定义项）
          title: '套装件数',
          dataIndex: 'numberOfSets',
          width: 120,
          className: 'replacecolor'
        },
        {
          title: '是否TC',
          dataIndex: 'isTc',
          width: 90,
          customRender: function(text) {
            if (text === '0') {
              return '否'
            }
            if (text === '1') {
              return '是'
            }
          },
          className: 'replacecolor'
        },
        // {
        //   title: 'HScode',
        //   dataIndex: 'hsCode',
        //   width: 120,
        //   className: 'replacecolor'
        // },
        // {
        //   title: '中文品名',
        //   dataIndex: 'chineseName',
        //   width: 120,
        //   className: 'replacecolor'
        // },

        {
          title: '成衣工厂',
          dataIndex: 'garmentFactory',
          width: 120,
          className: 'replacecolor'
        },
        {
          title: '报关单价',
          dataIndex: 'customsDeclarationUnitPrice',
          width: 90,
          className: 'replacecolor'
        },
        {
          title: '账套',
          dataIndex: 'account',
          width: 90,
          className: 'replacecolor'
        },
        {
          title: '推送结果',
          dataIndex: 'pushState',
          scopedSlots: { customRender: 'pushState' },
          fixed: 'right',
          width: 90,
          className: 'replacecolor'
        },
        {
          title: '单据状态',
          dataIndex: 'state',
          scopedSlots: { customRender: 'state' },
          fixed: 'right',
          width: 90,
          className: 'replacecolor'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operationSlot' },
          fixed: 'right',
          width: 160,
          className: 'replacecolor'
        }
      ],
      shipmentListData: [], // 发运明细数据

      // 查询条件
      queryParam: {
        documentNo: '', // 单据号
        startTime: '',
        endTime: '',
        // timeRange: [], // 查询条件  时间范围
        preDeliveryDate: '',
        salesman: '',
        itemNumber: '', // 款号
        refer: '',
        flourOrGarment: '', //类型
        pageNo: '' // 点击的页数
      },

      pagination: {
        // total: '',
        // current: 0,
        // pageSize: 0
      },
      dateFormat: 'YYYY-MM-DD',
      
    }
  },
  created() {
    // this.getShipmentList() // 渲染 发运明细列表
  },
  methods: {
    // 分页查询 发运明细
    getShipmentList() {
      this.$nextTick(() => {
         shipmentList(this.queryParam).then(res => {
          if (res.success) {
            this.shipmentListData = res.result.records
            for (var i=0; i<this.shipmentListData.length; i++){
              this.shipmentListData.randomId = randomUUID();
            }
            this.pagination = {
              total: res.result.total,
              current: res.result.current,
              pageSize: res.result.size
            }
          }
        })
        
      })
    },

    // 新增
    addShipDet() {
      this.$refs.addShipDetDrawer.syShippingDetailsItemList = [];
      this.$refs.addShipDetDrawer.visible = true
    },

    //  申报要素
    declareElements(record) {
      console.log(record)
      if (record.inventoryName == ""){
        this.$message.error('当前行存货名称为空，无法维护报关要素');
      }else{
        this.$refs.declareElementsModal.declareElementsModVis = true
        queryDeclarationElements({
          id: record.elementsId,
          syShippingids:record.itemIds
        }).then(res => {
          if (res.success) {
            // console.log('申报要素子表数据', res.result.syDeclarationElementsItemList)
            res.result['itemIds'] = record.itemIds;

            this.$refs.declareElementsModal.declareElements = res.result
            // 子表赋值
            this.$refs.declareElementsModal.declareElementsData = res.result.syDeclarationElementsItemList
            if(record.pushState == '1' && record.state == '1'){
              this.$refs.declareElementsModal.pushState = true
          }
          }
        })
      }
    },

    //  维护款号成分
    itemNumberElement(record) {
      this.$refs.itemNumEleModal.itemNumEleModVis = true

      this.$refs.itemNumEleModal.editItemNumber.itemIds = record.itemIds
      this.$refs.itemNumEleModal.editItemNumber.itemNumber = record.itemNumber
      this.$refs.itemNumEleModal.editItemNumber.materialComposition = record.materialComposition
      this.$refs.itemNumEleModal.editItemNumber.isTc = record.isTc
    },

    // 导出
    handleExportXls(fileName) {
  
      downFile('/shippingDetails/syShippingDetails/exportXls',this.queryParam).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对象
        }
      })
    },

    //  编辑
    edit(record) {
      this.$refs.editShipDetDrawer.visible = true

      queryByDetails({ id: record.id,itemIds: record.itemIds }).then(res => {
        if (res.success) {
          // console.log('编辑对象', res.result)
          this.$refs.editShipDetDrawer.editShipDet = res.result
          this.$refs.editShipDetDrawer.syShippingDetailsItemList = res.result.syShippingDetailsItemList
        }
      })
    },
    //  详情
    details(record) {
      this.$refs.detailsShipDetDrawer.visible = true
      // console.log('点击项的ID', record.id)
      queryByDetails({ id: record.id,itemIds: record.itemIds}).then(res => {
        if (res.success) {
          console.log('点击的对象', res.result)
          // 把通过id查询到的对象，赋值给子组件
          this.$refs.detailsShipDetDrawer.detailsShipDet = res.result
          this.$refs.detailsShipDetDrawer.syShippingDetailsItemList = res.result.syShippingDetailsItemList
        }
      })
    },

    //  提交
    submit(record) {
      console.log('点击id:', record.id)
      this.$nextTick(() => {
        submitShipment({ id: record.id, type: '1' }).then(res => {
          if (res.success) {
            console.log('提交成功，单据状态改为【已提交】')
            this.shipmentListData.state = '1'
            this.getShipmentList() // 渲染 发运明细列表
            this.$message.success('提交成功')
          }
        })
      })
    },
    // 取消提交
    cancelSubmit(record) {
      console.log('取消订单id:', record.id)
      this.$nextTick(() => {
        cancelSubmitShipment({ id: record.id, type: '2' }).then(res => {
          if (res.success) {
            console.log('取消提交成功，单据状态改为【仅保存】')
            this.shipmentListData.state = '0'
            this.getShipmentList() // 渲染 发运明细列表
            this.$message.success('取消提交成功')
          }
        })
      })
    },

    //  推送
    push(record) {
      console.log('推送id:', record.id)
      this.$nextTick(() => {
        pushShipment({ id: record.id }).then(res => {
          if (res.success) {
            console.log('推送成功，推送状态【推送成功】')
            this.shipmentListData.pushState = '1'
            this.getShipmentList() // 渲染 发运明细列表
            this.$message.success('推送成功')
          }
        })
      })
    },

    // 重新推送
    rePush(record) {
      console.log('重新推送record:', record)
      this.$nextTick(() => {
        rePushShipment({ id: record.id }).then(res => {
          if (res.success) {
            console.log(res)
            console.log('重新推送成功，推送状态【推送成功】')
            this.shipmentListData.pushState = '1'
            this.getShipmentList() // 渲染 发运明细列表
            this.$message.success('重新推送成功')
          }
        })
      })
    },

    //  删除
    handleDelete(record) {
      console.log('点击删除项id:', record.id)
      this.$nextTick(() => {
        deleteShipment({ id: record.id,itemIds: record.itemIds }).then(res => {
          console.log('res:', res)
          this.getShipmentList() // 渲染 发运明细列表
          this.$message.success('删除成功')
        })
      })
    },

    onDateChange(value, dateString) {
      console.log('查询开始时间', dateString[0], '查询结束时间', dateString[1])
      this.queryParam.startTime = dateString[0]
      this.queryParam.endTime = dateString[1]
    },

    onDateOk(value) {
      console.log('value', value)
    },

    deliveryDateChange(value, dateString) {
      console.log('预发货日期', dateString)
      this.queryParam.preDeliveryDate = dateString
    },

    searchQuery() {
      if(this.queryParam.flourOrGarment === ''){
       this.$message.error('请选择查询类型！');
      }else {
      this.queryParam.pageNo = ''
      this.getShipmentList()        
      }
    },

    searchReset() {
      this.queryParam.documentNo = ''
      this.queryParam.timeRange = []
      this.queryParam.startTime = ''
      this.queryParam.endTime = ''
      this.queryParam.preDeliveryDate = ''
      this.queryParam.salesman = ''
      this.queryParam.itemNumber = ''
      this.queryParam.refer = ''
      this.queryParam.isTc = ''
      this.queryParam.flourOrGarment = '', //类型
      this.shipmentListData = [] // 渲染 发运明细列表
    },

    // 分页变化时触发
    handleTableChange(pagination, filters, sorter) {
      this.queryParam.pageNo = pagination.current
      this.getShipmentList()
    },

    //关闭新增弹窗
    closeAdd(){
      this.queryParam.documentNo = ''
      this.queryParam.timeRange = []
      this.queryParam.startTime = ''
      this.queryParam.endTime = ''
      this.queryParam.preDeliveryDate = ''
      this.queryParam.salesman = ''
      this.queryParam.itemNumber = ''
      this.queryParam.refer = ''
      this.queryParam.isTc = ''
      this.queryParam.flourOrGarment = '', //类型
      this.shipmentListData = [] // 渲染 发运明细列表
    }
  }
}
</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;
// }
/deep/ .ant-form-item {
  // margin-bottom: 0 !important;
}
</style>
