<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="orderNo">
            <el-input
              v-model="queryParams.orderNo"
              placeholder="请输入单据编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据类型" prop="orderType">
            <DictSelect v-model="queryParams.orderType" placeholder="请选择单据类型" dict-type="WMS_REGULAR_CHECK_DOCUMENT_TYPE" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料编码" prop="materialNo">
            <el-input
              v-model="queryParams.materialNo"
              placeholder="请输入物料编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </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="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="wmsLabelMasterId">
                      <el-input
                        v-model="model.wmsLabelMasterId"
                        placeholder="请输入物料条码"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="仓库" prop="stockCode">
                      <el-input
                        v-model="model.stockCode"
                        placeholder="请输入仓库"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="创建时间" prop="createTime">
                      <el-date-picker
                        v-model="model.createTime"
                        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>
                </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="['wms:stock-check-detail:create']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:stock-check-detail:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          :loading="checkLoading"
          @click="handleSynchronous"
        >同步</el-button> -->
        <ManualSynchSelect @writeSuccess="getList" />
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-thumb"
          size="mini"
          :loading="checkLoading"
          @click="handleCheck"
        >盘点</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"
          v-loading="loading"
          :height="height"
          border
          :data="list"
        >
          <el-table-column
            v-if="columnsList[0].visible"
            :key="Math.random()"
            label="单据编号"
            align="center"
            width="150"
            show-overflow-tooltip
            prop="orderNo"
          />
          <el-table-column
            v-if="columnsList[1].visible"
            :key="Math.random()"
            label="单据类型"
            width="100"
            align="center"
            prop="orderType"
          >
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.WMS_REGULAR_CHECK_DOCUMENT_TYPE" :value="scope.row.orderType" />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[2].visible"
            :key="Math.random()"
            label="物料编码"
            align="center"
            min-width="130"
            show-overflow-tooltip
            prop="materialNo"
          />
          <el-table-column
            v-if="columnsList[3].visible"
            :key="Math.random()"
            label="物料名称"
            align="center"
            width="120"
            show-overflow-tooltip
            prop="materialName"
          />
          <el-table-column
            v-if="columnsList[4].visible"
            :key="Math.random()"
            label="物料条码"
            min-width="130"
            show-overflow-tooltip
            align="center"
            prop="wmsLabelMasterId"
          />
          <el-table-column
            v-if="columnsList[5].visible"
            :key="Math.random()"
            label="帐存数量"
            width="100"
            show-overflow-tooltip
            align="center"
            prop="stockQty"
          />
          <el-table-column
            v-if="columnsList[6].visible"
            :key="Math.random()"
            label="盘点数量"
            align="center"
            prop="checkQty"
            width="100"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[7].visible"
            :key="Math.random()"
            label="盘赢盘亏数量"
            align="center"
            width="120"
            show-overflow-tooltip
            prop="differQty"
          />
          <el-table-column
            v-if="columnsList[12].visible"
            :key="Math.random()"
            label="回写标识"
            align="center"
            width="120"
            show-overflow-tooltip
            prop="erpWriteFlag"
          >
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.ERP_WRITE_FLAG" :value="scope.row.erpWriteFlag" />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[13].visible"
            :key="Math.random()"
            label="回写错误消息"
            align="center"
            width="160"
            show-overflow-tooltip
            prop="erpErrMsg"
          />
          <el-table-column
            v-if="columnsList[8].visible"
            :key="Math.random()"
            label="单位"
            width="80"
            show-overflow-tooltip
            align="center"
            prop="unit"
          />
          <el-table-column
            v-if="columnsList[9].visible"
            :key="Math.random()"
            label="仓库"
            width="120"
            show-overflow-tooltip
            align="center"
            prop="stockName"
          />
          <el-table-column
            v-if="columnsList[10].visible"
            :key="Math.random()"
            label="备注"
            width="120"
            show-overflow-tooltip
            align="center"
            prop="remark"
          />
          <el-table-column
            v-if="columnsList[11].visible"
            :key="Math.random()"
            label="创建时间"
            align="center"
            prop="createTime"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="80"
            fixed="right"
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['wms:stock-check-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"
    />
    <!-- 盘点操作 -->
    <RegularlyCheck ref="regularlyCheck" @complete="getList" />

    <!-- 手动同步选择要同步的盘点单 -->

  </div>
</template>

<script>
import
{
  createStockCheckDetail,
  updateStockCheckDetail,
  deleteStockCheckDetail,
  getStockCheckDetail,
  getStockCheckDetailPage,
  exportStockCheckDetailExcel
}
  from '@/api/wms/inLibrary/periodicInventory'
import { getFormColumnsList } from '@/api/system/saveColumns/index'
import { mapGetters } from 'vuex'
import { isArray } from 'min-dash'
import RegularlyCheck from './components/RegularlyCheck.vue'
import ManualSynchSelect from './components/ManualSynchSelect.vue'

export default {
  name: 'StockCheckDetail',
  components: {
    RegularlyCheck,
    ManualSynchSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 盘点遮罩层
      checkLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盘赢盘亏列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 高级查询参数
      advParams: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        masterId: null,
        orderNo: null,
        orderType: null,
        materialNo: null,
        materialName: null,
        wmsLabelMasterId: null,
        stockQty: null,
        checkQty: null,
        differQty: null,
        unit: null,
        stockCode: null,
        remark: null,
        createTime: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderNo: [{ required: true, message: '单据编号不能为空', trigger: 'blur' }],
        orderType: [{ required: true, message: '单据类型不能为空', trigger: 'change' }],
        materialNo: [{ required: true, message: '物料编码不能为空', trigger: 'blur' }]
      },
      // 显示隐藏列参数
      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 },
        { key: 12, label: '回写标识', visible: true },
        { key: 13, label: '回写错误消息', visible: true }
      ],
      // 显示隐藏持久化参数
      columnsList: []
    }
  },
  // 获取当前登录用户id
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    // 获取显隐列列表
    this.getColumnsList()
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      const params = {
        ...this.queryParams,
        ...this.advParams
      }
      getStockCheckDetailPage(params).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,
        masterId: undefined,
        orderNo: undefined,
        orderType: undefined,
        materialNo: undefined,
        materialName: undefined,
        wmsLabelMasterId: undefined,
        stockQty: undefined,
        checkQty: undefined,
        differQty: undefined,
        unit: undefined,
        stockCode: undefined,
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.advParams = {}
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加盘赢盘亏'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id
      getStockCheckDetail(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改盘赢盘亏'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        // 修改的提交
        if (this.form.id != null) {
          updateStockCheckDetail(this.form).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
          return
        }
        // 添加的提交
        createStockCheckDetail(this.form).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除盘赢盘亏编号为"' + id + '"的数据项?').then(function() {
        return deleteStockCheckDetail(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      const params = { ...this.queryParams }
      params.pageNo = undefined
      params.pageSize = undefined
      this.$modal.confirm('是否确认导出所有盘赢盘亏数据项?').then(() => {
        this.exportLoading = true
        return exportStockCheckDetailExcel(params)
      }).then(response => {
        this.$download.excel(response, '盘赢盘亏.xls')
        this.exportLoading = false
      }).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
        }
      })
    },
    // 高级查询
    advQuery(advQueryParams) {
      this.advParams = advQueryParams
      this.handleQuery()
    },
    // 盘点
    handleCheck() {
      this.$refs.regularlyCheck.open = true
    }
  }
}
</script>
