<template>
<div class="creator">
  <div class="creator__body">
    <el-collapse v-model="activeNames">
      <el-form
        inline
        label-position="top"
        :model="formData"
        :rules="rules"
        :disabled="mode === 'detail'"
      >
        <el-collapse-item title="关键信息" name="1">
          <el-form-item label="盘点单">
            <el-input v-model="formData.countNo" disabled></el-input>
          </el-form-item>
          <template v-for="selector in selectors">
            <el-form-item :key="selector.prop" :label="selector.label" :prop="selector.prop">
              <el-select
                :disabled="selector.prop === 'status' || selector.prop === 'countType'"
                v-model="formData[selector.prop]"
              >
                <template v-for="item in $keys.inventory.count[selector.prop]">
                  <el-option
                    :key="item.id"
                    :label="item.name"
                    :value="item.key"
                  ></el-option>
                </template>
              </el-select>
            </el-form-item>
          </template>
          <el-form-item label="监盘人" prop="monitorOp">
            <PublicQuery
              single
              cfgKey="invWmsOperator"
              :baseUrl="baseUrl"
              title="监盘人"
              :valueField.sync="formData.monitorOp"
              :textField.sync="formData.monitorOpCn"
            ></PublicQuery>
          </el-form-item>
          <el-form-item label="上次盘点单号">
            <el-input v-model="formData.parentCountNo" disabled></el-input>
          </el-form-item>
        </el-collapse-item>

        <el-collapse-item title="盘点条件" name="2">
          <el-form-item label="货主" prop="ownerCode">
            <PublicQuery
              :disabled="(detailData.status !== '00') && mode !== 'create'"
              title="货主"
              :baseUrl="baseUrl"
              cfgKey="invWmsCustomer"
              :valueField.sync="formData.ownerCode"
              :textField.sync="formData.ownerName"
            ></PublicQuery>
          </el-form-item>
          <el-form-item label="商品" prop="skuCode">
            <PublicQuery
              title="商品"
              cfgKey="invWmsSkus"
              :disabled="(detailData.status !== '00') && mode !== 'create'"
              :baseUrl="baseUrl"
              :valueField.sync="formData.skuCode"
              :textField.sync="formData.skuName"
              :before="beforeSelectSku"
              @change="skuChange"
            ></PublicQuery>
          </el-form-item>
          <el-form-item label="批次号" prop="lotNum">
            <el-input v-model="formData.lotNum"></el-input>
          </el-form-item>
          <el-form-item label="跟踪号" prop="traceId">
            <el-input v-model="formData.traceId"></el-input>
          </el-form-item>
          <el-form-item label="商品序列号管理" prop="skuIsSerial">
            <el-select v-model="formData.skuIsSerial">
              <el-option value="Y" label="是"></el-option>
              <el-option value="N" label="否"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="库位类型" prop="locUseType">
            <el-select multiple v-model="formData.locUseType">
              <template v-for="item in $keys.warehouseBasic.locUseType">
                <el-option :key="item.id" :value="item.key" :label="item.name"></el-option>
              </template>
            </el-select>
          </el-form-item>
          <!--共用查询框-->
          <template v-for="item in publicQueries">
            <el-form-item
              :key="item.valueField"
              :label="item.label"
              :prop="item.prop"
            >
              <!--如下textField写法可支持在textField为空时的传值, 子组件不会报错, 父组件也不会绑定同一个值 (formData.undefined)-->
              <PublicQuery
                :title="item.label"
                :baseUrl="baseUrl"
                :cfgKey="item.cfgKey"
                :valueField.sync="formData[item.valueField]"
                :textField.sync="item.textField === undefined ? false : formData[item.textField]"
                :single="item.single"
                :rowData.sync="item.rowData"
              ></PublicQuery>
            </el-form-item>
          </template>
          <el-form-item label="动盘时间从">
            <el-date-picker
              disabled
              v-model="formData.takeStartTime"
              value-format="yyyy-MM-dd 00:00:00"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="动盘时间到">
            <el-date-picker
              disabled
              v-model="formData.takeEndTime"
              value-format="yyyy-MM-dd 23:59:59"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="抽盘比例" prop="randomRate">
            <el-input disabled v-model="formData.randomRate"></el-input>
          </el-form-item>
          <el-form-item label="抽盘数量" prop="randomNum">
            <el-input disabled v-model="formData.randomNum"></el-input>
          </el-form-item>
        </el-collapse-item>

        <el-collapse-item title="批次属性" name="3">
          <LotAttrs
            :formData="formData"
            :queryParams="lotAttrsParams"
          ></LotAttrs>
        </el-collapse-item>
      </el-form>
      <el-collapse-item title="盘点明细" name="4">
        <template v-if="showTaskList">
          <TaskList
            :formData="formData"
            :needRefresh="refreshChildren"
            :mode="mode"
            @refreshForm="refreshForm"
          ></TaskList>
        </template>
      </el-collapse-item>
      <el-collapse-item title="操作信息" name="5" v-if="mode === 'detail'">
        <div class="operation-info">
          <el-col :span="6">创建人登录名: {{detailData.createLoginName}} ({{detailData.createUserNameCn}})</el-col>
          <el-col :span="6">创建时间: {{detailData.createTime}}</el-col>
          <el-col :span="6">修改人登录名: {{detailData.modifyLoginName}} ({{detailData.modifyUserNameCn}})</el-col>
          <el-col :span="6">修改时间: {{detailData.modifyTime}}</el-col>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>

  <div class="creator__foot">
    <template v-if="(mode !== 'detail' && detailData.status === '00') || mode === 'create'">
      <el-button v-auth="50300010201" type="primary" @click="confirm">保存</el-button>
    </template>
    <template v-if="mode === 'detail'">
      <el-button
        v-if="formData.status === '80'"
        v-auth="50300010309"
        type="primary"
        @click="e => operate(e, 'createAdjustment')"
      >生成调整单</el-button>
      <el-dropdown class="btn__item">
        <el-button type="primary">
          更多<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <template v-if="formData.status === '80'">
            <el-dropdown-item v-auth="50300010311" command="reCreateTask" @click.native="operate">生成复盘任务</el-dropdown-item>
            <!--<el-dropdown-item v-auth="50300010312" command="createSerialCount" @click.native="operate">生成序列号盘点</el-dropdown-item>-->
          </template>
          <el-dropdown-item v-if="formData.status === '70' || formData.status === '80'" v-auth="50300010305" command="closeCount" needconfirm @click.native="operate">关闭盘点</el-dropdown-item>
          <el-dropdown-item v-if="formData.status === '00' || formData.status === '10'" v-auth="50300010314" command="cancelCount" needconfirm @click.native="operate">取消盘点</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-dropdown v-auth="50300010315" class="btn__item" @command="toPrint">
        <el-button type="primary">
          打印<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-auth="50300010316" command="18010070101">打印盘点任务单</el-dropdown-item>
          <el-dropdown-item v-auth="50300010319" command="18010070102">Print Count Task List</el-dropdown-item>
          <el-dropdown-item v-auth="50300010317" command="18010070103">打印盘点差异单</el-dropdown-item>
          <el-dropdown-item v-auth="50300010320" command="18010070104">Print Count Diff List</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button type="primary" class="btn__item" @click="$router.back()">关闭</el-button>
    </template>
  </div>
</div>
</template>

<script>
import mixins from './mixins'
import routerMixins from '../../routerMixins'
import TaskList from './taskList/TaskList'

export default {
  mixins: [ mixins, routerMixins ],
  components: { TaskList },
  props: {},
  watch: {
    detailData: {
      immediate: true,
      handler (val) {
        if (this.mode !== 'create') {
          // 编辑模式可直接显示明细
          this.countNo = val.countNo
          this.showTaskList = true
          this.lotAttrsParams = {
            ownerCode: val.ownerCode,
            skuCode: val.skuCode,
          }
        }
        const locUseTypeStr = val.locUseType
        const locUseType = locUseTypeStr || ['PC', 'RS', 'CS', 'EA'] // 库位类型默认值
        this.formData = {
          countType: 'NC', // 默认为普通盘点
          countRange: '1', // 盘点范围 - 全盘
          countMethod: 'S', // 静态盘点
          countMode: 'B', // 盲盘
          ...this.detailData,
          locUseType,
        }
      }
    },
  },
  created () {
    this.mode = this.$route.params.mode || 'create'
    this.detailData = this.$route.params.detailData || {}
  },
  mounted () {
  },

  data () {
    return {
      lotAttrsParams: {},
      formData: {}, // 表单对象
      needRefresh: false, // 是否需要父路由刷新
      mode: 'create', // 模式
      detailData: {},
      activeNames: ['1', '2', '3', '4', '5'],
      // 表单验证
      rules: {
        countRange: [{ required: true, message: '盘点范围必选', trigger: 'change' }],
        countMethod: [{ required: true, message: '盘点方法必选', trigger: 'change' }],
        countMode: [{ required: true, message: '盘点模式必选', trigger: 'change' }],
        locUseType: [{ required: true, message: '库位类型必选', trigger: 'change' }],
      },
      // 共用查询框
      publicQueries: [
        { label: '库位从', valueField: 'fmLoc', textField: 'fmLoc', cfgKey: 'invWmsLoc', rowData: {}, single: true },
        { label: '库位到', valueField: 'toLoc', textField: 'toLoc', cfgKey: 'invWmsLoc', rowData: {}, single: true },
        { label: '区域', valueField: 'areaCode', textField: 'areaName', cfgKey: 'invWmsArea', rowData: {} },
        { label: '库区', valueField: 'zoneCode', textField: 'zoneName', cfgKey: 'invWmsZone', rowData: {} },
      ],
      // 时间框
      datePickers: [
        { label: '生产日期', prop: 'lotAtt01' },
        { label: '失效日期', prop: 'lotAtt02' },
        { label: '入库日期', prop: 'lotAtt03' },
      ],
      showTaskList: false, // 显示盘点明细
      refreshChildren: false, // 刷新子组件数据标识
    }
  },
  methods: {
    // 选商品前校验
    beforeSelectSku () {
      if (!this.formData.ownerCode) {
        this.$message.error('请先选择货主')
      } else {
        return {
          queryParams: {
            multiOwnerCodeParam: this.formData.ownerCode
          }
        }
      }
    },
    // 保存
    confirm () {
      const copy = { ...this.formData }
      copy.locUseType = copy.locUseType.join(',')
      const url = this.$API.inventory.count.create
      const param = { saveModel: JSON.stringify(copy) }
      this.$https.post(url, param)
        .then(data => {
          this.needRefresh = true
          this.countNo = data.data.countNo
          data.data.locUseType = data.data.locUseType.split(',')
          this.formData = { ...data.data }
          this.showTaskList = true
        })
    },
    // 选择了商品
    skuChange (skus) {
      let skuCode = '',
        ownerCode = ''
      // 多选则传空值
      if (skus.length === 1) {
        skuCode = skus[0].skuCode
        ownerCode = skus[0].ownerCode
      }
      this.lotAttrsParams = {
        skuCode,
        ownerCode,
      }
    },
    // 打印
    toPrint (command, vmNode) {
      const param = {
        title: vmNode.$el.innerHTML,
        qs: `_functionCode=${command}&countNo=${this.formData.countNo}`
      }
      this.$print(param)
    },
    // 操作
    operateConfirm (type) {
      const url = this.$API.inventory.count[type]
      const param = { countNos: this.formData.countNo }
      this.$https.post(url, param)
        .then(() => {
          this.refreshForm()
        })
    },
    // 操作后刷新表单
    refreshForm () {
      this.getDetail()
      this.needRefresh = true // 可通知列表更新
    },
    // 操作后重新获取详情
    getDetail () {
      const url = this.$API.inventory.count.detail
      const param = { countNo: this.formData.countNo }
      this.$https.post(url, param)
        .then(data => {
          data.data.locUseType = data.data.locUseType.split(',')
          this.formData = { ...data.data }
          this.setPreInfo() // 设置明细列表参数获取明细列表
        })
    },
    // 设置子组件参数
    setPreInfo () {
      this.refreshChildren = !this.refreshChildren
    },
  },
}
</script>

<style lang="scss" scoped>
.creator {
  overflow-y: auto;
  height: 100%;
}
.creator__body {
  height: calc(100% - 50px); // 减去 bottom 的高度
  border-bottom: 1px solid #ddd;
  overflow-x: hidden;
}
.el-collapse-item {
  margin-bottom: 20px;
}
.creator__foot {
  position: fixed;
  bottom: 20px;
}

.operation-info {
  text-align: center;
}
.btn__item {
  margin-left: 10px;
}
</style>
