<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="68px"
    >
      <QueryFormWrapper>
        <el-col :span="8">
          <el-form-item label="销售订单" prop="erpOrderNo">
            <el-input
              v-model="queryParams.erpOrderNo"
              placeholder="请输入销售订单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerName">
            <el-input
              v-model="queryParams.customerName"
              placeholder="请输入客户名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据日期" prop="erpOrderTime">
            <el-date-picker
              v-model="queryParams.erpOrderTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            />
          </el-form-item>
        </el-col>
        <div slot="right">
          <el-form-item label-width="0" class="text-right" style="word">
            <EasyAdvancedQuery class="mr10" label-width="98px" @advQuery="advQuery">
              <template #default="{model}">
                <el-row :gutter="10" type="flex">
                  <el-col :span="12">
                    <el-form-item label="单据状态" prop="status">
                      <el-select
                        v-model="model.status"
                        placeholder="请选择单据状态"
                        clearable
                        size="small"
                      >
                        <el-option
                          v-for="dict in getDictDatas(DICT_TYPE.WMS_SALE_ORDER_DELIVER_STATUS)"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="物料编码" prop="materialNo">
                      <el-input
                        v-model="model.materialNo"
                        placeholder="请输入物料编码"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="物料名称" prop="materialName">
                      <el-input
                        v-model="model.materialName"
                        placeholder="请输入物料名称"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="交货地点" prop="deliveryAddress">
                      <el-input
                        v-model="model.deliveryAddress"
                        placeholder="请输入交货地点"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </EasyAdvancedQuery>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </div>
      </QueryFormWrapper>

    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['dis:erpTask:query']"
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          :loading="synchronizationLoading"
          @click="handleSynchronization"
        >手动同步</el-button>
        <el-button
          v-hasPermi="['wms:sale-order:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
        <el-button
          type="primary"
          plain
          size="small"
          icon="el-icon-magic-stick"
          @click="handleGenerate"
        >生成出货通知单</el-button>
      </el-col>
      <right-toolbar
        :columns="columnsList"
        :show-search.sync="showSearch"
        @saveSetting="getColumnsList"
        @queryTable="getList"
      />
    </el-row>

    <!-- 列表 -->
    <AutoResizer :given-height="177">
      <template #default="{height}">
        <el-table
          v-if="columnsList.length > 0"
          ref="salesTable"
          v-loading="loading"
          :data="list"
          border
          :height="height"
          :span-method="arraySpanMethod"
          @selection-change="tableSelected"
        >
          <el-table-column
            type="selection"
            width="55"
            fixed="left"
            align="center"
          />
          <el-table-column
            v-if="columnsList[0].visible"
            :key="Math.random()"
            label="销售订单"
            align="center"
            prop="erpOrderNo"
            width="140"
            fixed="left"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[1].visible"
            :key="Math.random()"
            label="客户名称"
            align="center"
            prop="customerName"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[2].visible"
            :key="Math.random()"
            label="物料编码"
            align="center"
            prop="materialNo"
            width="130"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[3].visible"
            :key="Math.random()"
            label="物料名称"
            align="center"
            prop="materialName"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[4].visible"
            :key="Math.random()"
            label="规格"
            align="center"
            prop="materialModels"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[5].visible"
            :key="Math.random()"
            label="单位"
            align="center"
            prop="unitName"
            width="120"
          />
          <el-table-column
            :key="Math.random()"
            label="已退数量"
            align="center"
            prop="returnQty"
            width="120"
          />
          <el-table-column
            :key="Math.random()"
            label="剩余待出货数量"
            align="center"
            prop="nowDeliveredQty"
            width="120"
          />
          <el-table-column
            v-if="columnsList[6].visible"
            :key="Math.random()"
            label="已出货数量"
            align="center"
            prop="deliveredQty"
            width="120"
          />
          <el-table-column
            v-if="columnsList[7].visible"
            :key="Math.random()"
            label="应出货数量"
            align="center"
            prop="shouldDeliveredQty"
            width="120"
          />
          <el-table-column
            v-if="columnsList[8].visible"
            :key="Math.random()"
            label="交货地点"
            align="center"
            prop="deliveryAddress"
          />
          <el-table-column
            v-if="columnsList[9].visible"
            :key="Math.random()"
            label="交货时间"
            align="center"
            prop="deliveryTime"
            width="120"
          />
          <el-table-column
            v-if="columnsList[10].visible"
            :key="Math.random()"
            label="单据状态"
            align="center"
            prop="status"
            width="100"
          >
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.WMS_SALE_ORDER_DELIVER_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="单据类型" align="center" prop="documentType">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.WMS_SALE_ORDER_DOCUMENT_TYPE" :value="scope.row.documentType" />
        </template>
      </el-table-column> -->
          <el-table-column
            v-if="columnsList[11].visible"
            :key="Math.random()"
            label="单据日期"
            align="center"
            prop="erpOrderTime"
            width="120"
          />
          <el-table-column
            label="操作"
            align="center"
            width="80"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['wms:sale-order-detail:delete']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                class="text-danger"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </AutoResizer>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <ShipmentNotification
      ref="shipmentNotification"
      :current-rows="currentRows"
      @createComplete="getList"
      @notificationClose="notificationClose"
    />
  </div>
</template>

<script>
import { getSaleOrderPage, exportSaleOrderExcel, deleteSaleOrder } from '@/api/wms/orders/sale'
import { getErpTaskData } from '@/api/wms/orders/purchase'
import ShipmentNotification from './components/ShipmentNotification.vue'
import { getFormColumnsList } from '@/api/system/saveColumns/index'
import { mapGetters } from 'vuex'
import { isArray } from 'min-dash'

export default {
  name: 'SaleOrder',
  components: {
    ShipmentNotification
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      synchronizationLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售订单列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 选中的数据
      currentRows: [],
      // 高级查询参数
      advParams: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        erpId: null,
        erpOrderNo: null,
        erpOrderTime: [],
        customerCode: null,
        customerName: null,
        status: null,
        deliveryType: null,
        deliveryAddress: null,
        remark: null,
        documentType: null,
        tranType: null,
        deptCode: null,
        erpMdtime: [],
        createTime: [],
        erpMark: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 显示隐藏列参数
      columns: [
        { key: 0, label: '销售订单', visible: true },
        { key: 1, label: '客户名称', visible: true },
        { key: 2, label: '物料编码', visible: true },
        { key: 3, label: '物料名称', visible: true },
        { key: 4, label: '规格', visible: true },
        { key: 5, label: '单位', visible: true },
        { key: 6, label: '已出货数量', visible: true },
        { key: 7, label: '应出货数量', visible: true },
        { key: 8, label: '交货地点', visible: true },
        { key: 9, label: '交货时间', visible: true },
        { key: 10, label: '单据状态', visible: true },
        { key: 11, label: '单据日期', visible: true }
      ],
      // 显示隐藏持久化参数
      columnsList: []
    }
  },
  // 获取当前登录用户id
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    // 获取显隐列列表
    this.getColumnsList()
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      const allParams = { ...this.queryParams, ...this.advParams }
      getSaleOrderPage(allParams).then(response => {
        this.list = response.data.list
        this.total = response.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        erpId: undefined,
        erpOrderNo: undefined,
        erpOrderTime: undefined,
        customerCode: undefined,
        customerName: undefined,
        status: undefined,
        deliveryType: undefined,
        deliveryAddress: undefined,
        remark: undefined,
        documentType: undefined,
        tranType: undefined,
        deptCode: undefined,
        erpMdtime: undefined,
        erpMark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.advParams = {}
      this.handleQuery()
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      const params = { ...this.queryParams }
      params.pageNo = undefined
      params.pageSize = undefined
      this.$modal.confirm('是否确认导出所有销售订单数据项?').then(() => {
        this.exportLoading = true
        return exportSaleOrderExcel(params)
      }).then(response => {
        this.$download.excel(response, '销售订单.xls')
        this.exportLoading = false
      }).catch(() => {})
    },
    // 手动同步
    handleSynchronization() {
      const params = {
        type: 2
      }
      this.$modal.confirm('您确认要从ERP同步生产订单的数据吗？').then(() => {
        this.synchronizationLoading = true
        getErpTaskData(params).then(() => {
          this.$modal.msgSuccess('同步成功')
          this.synchronizationLoading = false
        })
      }).finally(() => {
        this.synchronizationLoading = false
      })
    },
    // 表格行合并
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      const newData = this.list.map((item, index) => {
        const filterData = this.list.filter(ele => {
          return item.erpOrderNo === ele.erpOrderNo
        })
        const dataIndex = this.list.findIndex(eleIndex => {
          return item.erpOrderNo === eleIndex.erpOrderNo
        })
        if (index === dataIndex) {
          item.rowspan = filterData.length
        } else {
          item.rowspan = 0
        }
        return newData
      })
      if (columnIndex === 0 || columnIndex === 1) {
        return {
          rowspan: row.rowspan,
          colspan: 1
        }
      } else {
        return false
      }
    },
    // 出货通知单
    handleGenerate() {
      if (this.currentRows.length <= 0) {
        this.$modal.msgWarning('请选择您要生成出货通知单的数据!')
        return
      }
      this.$refs.shipmentNotification.open = true
    },
    // 表格选中
    tableSelected(val) {
      const selectOrder = val.map(item => {
        const { erpOrderNo } = item
        return erpOrderNo
      })
      const mergeData = this.list.filter(item => {
        if (selectOrder.indexOf(item.erpOrderNo) > -1) {
          return item
        }
      })
      this.currentRows = mergeData
    },
    notificationClose() {
      this.$refs.salesTable.clearSelection()
      this.currentRows = []
    },
    // 高级查询
    advQuery(advQueryParams) {
      this.advParams = advQueryParams
      this.handleQuery()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const { id, materialNo } = row
      const message = `是否确认删除物料编码为【${materialNo}】的销售订单?`
      this.$modal.confirm(message).then(function() {
        return deleteSaleOrder(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    // 获取显示隐藏列
    getColumnsList() {
      const { componentName } = this.$route.meta || null
      const params = {
        userId: this.userId,
        vueForm: componentName
      }
      getFormColumnsList(params).then(res => {
        if (isArray(res.data)) {
          this.columnsList = res.data.length === 0 ? this.columns : res.data
          // 对比默认数据和接口数据，将缺失的列添加到接口数据中
          this.columnsList = this.columns.reduce((acc, defaultColumn) => {
            const found = res.data.find(apiColumn => apiColumn.key === defaultColumn.key)
            if (!found) {
              acc.push({ ...defaultColumn, vueForm: componentName, userId: this.userId, id: null })
            }
            return acc
          }, res.data)
        } else {
          this.columnsList = this.columns
        }
      }).catch((err) => {
        if (err) {
          this.columnsList = this.columns
        }
      })
    }
  }
}
</script>

