<!-- 仓库--组装拆卸单 -->
<template>
  <div class="main-container order-mc-bg">
    <div class="sale-container">
      <!-- 顶部按钮组 -->
      <toolBtn @actionhandel="actionhandel" :btnType="btnType"></toolBtn>
      <!-- 列表 -->
      <div class="sale-page-body">
        <!-- 表头 -->
        <div class="sale-page-table-header" ref="getSaleTableHeader">
          <el-form :inline="true">
            <el-row class="form-row1">
              <el-col :span="20">
                <el-row :gutter="2">
                  <el-col :span="4">
                    <el-form-item class="Iisshow" label="单据编号">
                      <el-input v-model.trim="search.billNo" placeholder="请输入单据编号" class="f-12"></el-input>
                      <div :data-clipboard-text="search.billNo" @click="saleOrderCopy" class="copyBtn">
                        <i class="el-icon-document-copy" />
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="单据状态">
                      <el-select v-model="search.documentStatus" placeholder="请选择" clearable>
                        <el-option class="f-12" v-for="(value, key, index) in documentStatuslist" :key="key + index"
                          :label="value" :value="key"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="仓库">
                      <el-select v-model="search.stockId" filterable placeholder="请选择">
                        <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item class="Iisshow" label="产品">
                      <el-input v-model.trim="search.productKey" placeholder="请输入物料名称/编码/SKU" class="f-12"></el-input>
                      <div :data-clipboard-text="search.productKey" @click="saleOrderCopy" class="copyBtn">
                        <i class="el-icon-document-copy" />
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="4" class="form-row-lastcol">
                <el-row :gutter="2">
                  <el-col :span="24">
                    <el-form-item class="form-group1">
                      <el-button size="small" @click="resetSearch">重置</el-button>
                      <el-button type="primary" size="small" @click="searchData">搜索</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <!-- 列表 -->
        <div class="sale-page-table-body">
          <el-table class="table-box" :data="tableData" ref="tableInfoRef" border v-loading="isLoading"
            element-loading-text="加载中，请稍后..." element-loading-spinner="el-icon-loading"
            style="width: 100%;font-size:12px" :max-height="heightNum" :header-cell-class-name="headerRigthMethod"
            @selection-change="handleSelectionChange" @row-dblclick="openDetailsDB">
            <el-table-column type="selection" align="center" width="40" fixed />
            <el-table-column prop="billNo" label="拆卸单号" align="left" fixed width="187">
              <template #default="scope">
                <span style="color: #4178D5" @click="jump(scope.row)">{{ scope.row.billNo }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="materialNumberProduct" label="成品编码" align="left" width="172" />
            <el-table-column prop="specificationProduct" label="成品规格型号" align="left" width="280" />
            <el-table-column prop="materialNameProduct" label="成品名称" align="left" width="150" />
            <el-table-column prop="unitNameProduct" label="成品单位" align="center" width="172" />
            <el-table-column prop="qtyProduct" label="成品数量" align="right" width="100" />
            <el-table-column prop="stockNameProduct" label="成品仓库" align="left" width="120" />
            <el-table-column prop="customerNameProduct" label="成品客户" align="left" width="172" />
            <el-table-column prop="customerStockNameProduct" label="成品客户仓库" align="left" width="120" />
            <el-table-column prop="materialNumber" label="子物料编码" align="left" width="172" />
            <el-table-column prop="specification" label="子物料规格型号" align="left" width="280" />
            <el-table-column prop="materialName" label="子物料名称" align="left" width="150" />
            <el-table-column prop="unitName" label="子物料单位" align="center" width="172" />
            <el-table-column prop="qty" label="子物料数量" align="right" width="100" />
            <el-table-column prop="stockName" label="子物料仓库" align="left" width="120" />
            <!-- <el-table-column prop="subStockName" label="子物料仓位" align="left" width="200" /> -->
            <el-table-column prop="customerName" label="子物料客户" align="left" width="172" />
            <el-table-column prop="customerStockName" label="子物料客户仓库" align="left" width="120" />
            <el-table-column prop="date" label="日期" align="left" width="83" />
            <el-table-column prop="documentStatus" label="单据状态" align="center" width="72" />
            <el-table-column prop="billType" label="单据类型" align="center" width="72" />
            <el-table-column prop="note" label="备注" align="center" width="225" />
          </el-table>
        </div>
      </div>
      <!-- 底部 -->
      <div class="sale-page-footer">
        <div class="footer-right">
          <el-pagination :page-sizes="[50, 100, 150]" :page-size="search.pageSize"
            layout="slot,sizes, total,prev,pager, next,jumper" :total="orderTotal" popper-class="每页显示"
            :currentPage="search.pageNo" @size-change="handleSizeChange" @current-change="handleCurrentChange">
            <span class="total-select-item">
              共选中
              <text style="text-align:center;color:#4178D5;padding:0 1px;">{{
                multipleSelection?
              multipleSelection.length : 0
              }}</text>行
            </span>
          </el-pagination>
        </div>
        <div class="footer-pagination-total-page">
          <span>共{{ Math.ceil(orderTotal / search.pageSize) }}页</span>
        </div>
      </div>
    </div>
    <!-- 操作结果 -->
    <el-dialog title="操作结果" v-model="dialogVisible" width="40%">
      <div class="sale-page-table-body">
        <el-table class="table-box" :data="tableInfo" height="300" border :header-cell-class-name="headerRigthMethod"
          id="tableInfo-table">
          <el-table-column prop="date" label="序号" width="50">
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="orderNo" label="拆卸订单号" width="200"></el-table-column>
          <el-table-column prop="a" label="指令" width="110">
            <template #default>
              <span>{{ actionType === 'submit' ? '提交' : actionType === 'revoke' ? '撤销' : actionType === 'audit' ?
                '审核' : actionType === 'de-approval' ? '反审' : actionType === 'delet' ? '删除' : actionType === 'finish' ?
                  '完工' : actionType === 'close-case' ? '结案' : actionType === 'de-excute-start' ? '反执行至开工' : actionType ===
                    'de-approval' ? '反审' : actionType === 'delet' ? '删除' : actionType === 'finish' ? '完工' : actionType ===
                      'close-case' ? '结案' : actionType === 'de-excute-finish' ? '反执行至完工' : ''
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结果" width="80">
            <template #default="scope">
              <span :style="{ 'txt-Red': scope.row.isSuccess }">{{ scope.row.isSuccess ? '成功' : '失败' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="msg" label="信息">
            <template #default="scope">
              <span class="txt-Red">{{ scope.row.msg }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <span class="f-12 ext-black-light" style="margin-right: 25px;">共{{ tableInfo && tableInfo.length > 0 ?
            tableInfo.length : 0
          }}条</span>
          <el-button size="small" @click="handelhtmlToExcel('tableInfo-table', '操作结果'); dialogVisible = false">导 出
          </el-button>
          <el-button type="primary" size="small" @click="dialogVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { transformTimestamp, exporthandel, htmlToExcel } from '@/utils/pubulic.js'
import { orderCopy } from '@/utils/takeMethods'
export default {
  name: 'DisassembleOrder',
  data () {
    return {
      orderTotal: 0,
      actionType: '', //判断点击的顶部那个按钮
      tableInfo: [], //操作结果
      isLoading: false, //表格加载数据
      documentStatuslist: [], // 单据状态
      multipleSelection: [], // 列表选中集合
      btnType: [
        'save',
        'copy',
        'close-case',
        'split-order',
        'close',
        'de-close',
        'close',
        'print-aterial-list',
        'finish',
        'close-case',
        'de-excute-start',
        'de-excute-finish',
        'finish',
        'push-down',
        'print-brower',
        'query'
      ], // 不需要显示的顶部按钮类型
      warehouseList: [], // 仓库数据
      dialogVisible: false, // 操作弹框显示
      // 搜索条件
      search: {
        orgId: '', // 组织Id(所有列表页都需要 全局)
        billNo: '', //单据编号（采购入库单号）
        documentStatus: '', //单据状态
        stockId: '', // 仓库ID
        productKey: '', // 产品（关键字）：物料表中的->>编码、名称、规格型号
        pageNo: 1, // 页码
        pageSize: 50 // 页数
      },
      tableData: [],
      selectItem: 0,
      rowShow: false,
      heightNum: 0,
      windowHeight: 0,
      isDown: true
    }
  },
  computed: {
    ...mapState({
      orgId: state => (state && state.org && state.org.orgId ? state.org.orgId : null)
    }),
    transformTime: function () {
      return function (value) {
        return transformTimestamp(value)
      }
    }
  },
  created () {
    this.windowHeight = document.documentElement.clientHeight
    this.heightNum = this.windowHeight - (40 + 30 + 54 + 34 + 34 + 34 + 16 + 16)
    this.search.orgId = this.orgId
    this.Init()
  },
  activated () {
    // 键盘监听事件
    document.addEventListener('keyup', this.keyupFn, false)
  },
  deactivated () {
    document.removeEventListener('keyup', this.keyupFn, false)
  },
  watch: {
    orgId (value) {
      if (value) {
        this.search.orgId = value
        // 监听组织切换 ，数据初始化
        this.Init()
      }
    }
  },
  mounted () { },
  methods: {
    keyupFn (e) {
      if (e.keyCode === 13) {
        // enter见搜索
        this.searchData()
      }
    },
    // 初始化
    Init () {
      this.getwarehouse()
      this.getdisassembleOrder()
      this.getStatus()
    },
    // 操作弹框导出
    handelhtmlToExcel (domid, title) {
      htmlToExcel(domid, title)
    },
    // 重置
    resetSearch () {
      this.search = {
        orgId: this.orgId, // 组织Id(所有列表页都需要 全局)
        billNo: '', //单据编号（采购入库单号）
        documentStatus: '', //单据状态
        stockId: '', // 仓库ID
        productKey: '', // 产品（关键字）：物料表中的->>编码、名称、规格型号
        pageNo: 1, // 页码
        pageSize: 50 // 页数
      }
      this.getdisassembleOrder()
    },
    // 双击计入
    openDetailsDB (row, column) {
      let typeStr1 = row.documentStatus === '重新审核' || row.documentStatus === '创建' ? 'edit' : 'see'
      this.$router.push({ path: '/warehouse/other/disassembleOrderSet', query: { type: typeStr1, productId: row.id } })
    },
    // 点击生产订单查看或者是编辑
    jump (item) {
      // 只有创建和重新审核的单据才能做修改，其余都是查看
      let typeStr = item.documentStatusKey === 'a' || item.documentStatusKey === 'd' ? 'edit' : 'see'
      this.$router.push({ path: '/warehouse/other/disassembleOrderSet', query: { type: typeStr, productId: item.id } })
    },
    // 订单号 复制按钮
    saleOrderCopy () {
      orderCopy()
    },
    // 获取仓库
    getwarehouse () {
      // 获取仓库
      this.warehouseList = []
      this.$http.get('SysConfig/GetWarehouseByOrg/' + this.orgId).then(req => {
        if (req.status === 200) {
          this.warehouseList = req.data
        }
      })
    },
    // 获取需要状态列表---[单据状态，领料状态，业务状态]
    getStatus () {
      this.$http.get('Disassembly/status/get').then(r => {
        if (r.status === 200) {
          this.documentStatuslist = r.data.documentStatus
        }
      })
    },
    // 获取盘点单数据
    getdisassembleOrder () {
      this.isLoading = true
      this.$http.post('Disassembly/list', this.search).then(res => {
        if (res.status === 200) {
          this.isLoading = false
          this.tableData = res.data
          this.orderTotal = res.totalCount
        }
      })
    },
    // 顶部公共按钮操作
    actionhandel (type) {
      this.actionType = type
      // 点击新增
      if (type === 'add') {
        this.$router.push({ path: '/warehouse/other/disassembleOrderSet', query: { type: 'add', id: '', sjtag: Math.random() * 36 } })
      }
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        let nweArysize = 0
        // 单据id集合 （有去重）
        let newArry = [
          ...new Set(
            this.multipleSelection.map(item => {
              return item.id
            })
          )
        ]
        // 取单据订单号
        let orderNoArry = [
          ...new Set(
            this.multipleSelection.map(item => {
              return item.billNO
            })
          )
        ]
        this.OrderNoNames = []
        this.OrderNoNames = orderNoArry
        // 明细id集合 （有去重）
        let detailsIds = [
          ...new Set(
            this.multipleSelection.map(item => {
              return item.detailId
            })
          )
        ]
        this.OrdedetailIds = []
        this.OrdedetailIds = detailsIds
        // 单据id 集合的size
        nweArysize = new Set(
          this.multipleSelection.map(item => {
            return item.productId
          })
        ).size
        // 点击复制
        if (type === 'copy') {
          if (nweArysize !== 1 && nweArysize > 0) {
            this.$message.error({ message: '只能克隆单号相同的生产订单', showClose: true })
          } else {
            this.$router.push({
              path: '/warehouse/other/disassembleOrderSet',
              query: {
                type: 'copy',
                productId: this.multipleSelection[0].id
              }
            })
          }
        }
        // 点击提交
        if (type === 'submit') {
          this.toolarFn('Disassembly/submit/status', newArry)
        }
        // 点击撤销
        if (type === 'revoke') {
          this.toolarFn('Disassembly/revoke', newArry)
        }
        // 点击审核
        if (type === 'audit') {
          this.toolarFn('Disassembly/check', newArry)
        }
        // 点击反审核
        if (type === 'de-approval') {
          this.toolarFn('Disassembly/recheck', newArry)
        }
        // 点击删除
        if (type === 'delet') {
          this.toolarFn('Disassembly/delete', newArry)
        }
      } else {
        //按列表字段导出,点击全部导出
        if (type !== 'add' && type !== 'refresh' && type !== 'list-export' && type !== 'all-export') {
          this.$message.error({ message: '请先勾选', showClose: true })
        }
      }
      if (type === 'list-export' || type === 'all-export') {
        exporthandel(type === 'list-export' ? 'Disassembly/Export' : 'Disassembly/ExportAll', this.search)
      }
      // 点击刷新
      if (type === 'refresh') {
        this.getdisassembleOrder()
      }
    },
    // 顶部操作方法-公共部分封装下
    toolarFn (path, newArry, detailsIds) {
      let formdata = detailsIds
        ? {
          ids: newArry,
          detailsIds: detailsIds
        }
        : { ids: newArry }
      this.$http.post(path, formdata).then(res => {
        if (res.status === 200) {
          this.dialogVisible = true
          this.tableInfo = res.data
          this.search.pageNo = 1
          this.getdisassembleOrder()
        }
      })
    },
    // 下单日期改变
    time1Chang (value) {
      if (value && value.length > 0) {
        this.search.beginDate = value[0]
        this.search.endDate = value[1]
      } else {
        this.search.beginDate = ''
        this.search.endDate = ''
      }
    },
    // 搜索事件
    searchData () {
      this.search.pageNo = 1
      this.getdisassembleOrder()
    },

    headerRigthMethod ({ row, column, rowIndex, columnIndex }) {
      return 'headerRight'
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handleSizeChange (val) {
      this.search.pageNo = 1
      this.search.pageSize = val
      this.Init()
    },
    handleCurrentChange (val) {
      this.search.pageNo = val
      this.Init()
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/style/saleOrder/saleOrderCommon.scss';
@import '@/assets/style/saleOrder/orderList.scss';
@import '@/assets/style/saleOrder/common.scss';
</style>