<template>
  <div>
    <a-modal @cancel="handleCancel" :visible="stockVisible" :title="title" width="90%">
      <a-spin :spinning="confirmLoading">
        <edit-form
          :spinnerList="spinnerList"
          :depotList="deoptData"
          :form="form"
          :rules="rules"
          :stockVisible="stockVisible"
          ref="editForm"
          :total="dataSource.length || 0"
          openType="detail"
          :stockType="stockType"
          @getForm="getForm"
          @clear="onClearList"
        ></edit-form>
        <a-divider />
        <div>
          <div>
            <a-form :form="queryParam" ref="form">
              <a-row class="form-row" :gutter="24">
                <a-col :lg="6" :md="12" :sm="24" class="form-col">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品类别">
                    <!-- <a-input disabled placeholder="请输入" v-model="queryParam.categoryId" /> -->
                    <a-tree-select
                      style="width: 100%"
                      :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                      allow-clear
                      :treeData="categoryTree"
                      v-model="queryParam.categoryId"
                      placeholder="请选择商品类别"
                    >
                    </a-tree-select>
                  </a-form-item>
                </a-col>
                <a-col :lg="6" :md="12" :sm="24" class="form-col">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品名称">
                    <a-input placeholder="请输入" v-model="queryParam.name" />
                  </a-form-item>
                </a-col>
                <a-col :lg="6" :md="12" :sm="24" class="form-col">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="批次号">
                    <a-input placeholder="请输入" v-model="queryParam.batchNumber" />
                  </a-form-item>
                </a-col>
                <a-col :lg="6" :md="12" :sm="24" class="form-col">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="仓位货架">
                    <a-input placeholder="请输入" v-model="queryParam.position" />
                  </a-form-item>
                </a-col>
                <a-col :lg="6" :md="12" :sm="24" class="form-col">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否存在数量差异">
                    <a-select placeholder="请选择" v-model="form.isDifference" :options="isDifferenceData"> </a-select>
                  </a-form-item>
                </a-col>
                <span>
                  <a-col :md="6" :sm="24">
                    <a-button type="primary" @click="onSearch">查询</a-button>
                    <a-button style="margin-left: 8px" @click="onReset">重置</a-button>
                  </a-col>
                </span>
              </a-row>
            </a-form>
          </div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            @change="handleTableChange"
          >
            <!-- <template v-for="col in colList" :slot="col" slot-scope="text, record">
              <div :key="col">
                <a-input v-if="editableData[record.id]" v-model="editableData[record.id][col]" style="margin: -5px 0" />
                <template v-else>
                  {{ col }}
                </template>
              </div>
            </template> -->
            <span slot="action" v-if="openType !== 'detail'" slot-scope="text, record">
              <a type="text" @click="handleEdit(record)">编辑</a>
            </span>
            <template slot="inventory" slot-scope="value, record">
              {{ parseInt(value) }}
            </template>
          </a-table>
        </div>
      </a-spin>
      <template slot="footer">
        <a-button @click="handleCancel">取消</a-button>
        <a-button v-if="isShowBtn" @click="handleOk">完成盘点</a-button>
        <a-button v-if="isShowBtn" @click="handleUpdate" type="primary">确定更新盘点数据</a-button>
      </template>
    </a-modal>
    <j-select-material-modal
      @ok="getGoods"
      @all="findAllSelect"
      ref="selectModal"
      :multi="true"
      :isStock="true"
    ></j-select-material-modal>
    <a-modal @cancel="editVisible = false" @ok="onSubmitGoods" :visible="editVisible" title="编辑" width="50%">
      <a-form-model :model="editForm" :rules="editFormRules" ref="editFormModel">
        <a-form-model-item label="盘点任务名称" :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }" prop="name">
          <a-input disabled v-model="editForm.name" placeholder="请输入"></a-input>
        </a-form-model-item>
        <a-form-model-item label="批次号" :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }" prop="batchNumber">
          <a-input disabled v-model="editForm.batchNumber" placeholder="请输入"></a-input>
        </a-form-model-item>
        <a-form-model-item label="实际库存" :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }" prop="newInventory">
          <a-input-number placeholder="请输入" v-model="editForm.newInventory" @change="handleChangeNewInventory" :min="0" style="width:100%" />
        </a-form-model-item>
        <a-form-model-item label="实际仓位货架" :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }" prop="newPosition">
          <a-input v-model="editForm.newPosition" placeholder="请输入"></a-input>
        </a-form-model-item>
        <a-form-model-item :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }" prop="differenceCount">
          <template slot="label">
            差异数量
            <span>
              <a-tooltip>
                <template slot="title">
                  盘盈是正数，盘亏是负数
                </template>
                <a-icon type="question-circle" />
              </a-tooltip>
            </span>
          </template>
          <span :class="editForm.differenceCount!==0?'red-num':''">{{editForm.differenceCount}}</span>
        </a-form-model-item>
        <a-form-model-item label="差异原因" :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }" prop="differenceReason">
          <a-input v-model="editForm.differenceReason" placeholder="请输入"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { findBySelectOrgan, queryMaterialCategoryTreeList, getAllOrganizationTreeByUser } from '@/api/api'

import editForm from './editForm.vue'
import table from '../utils/table'
import JSelectMaterialModal from '../../../components/jeecgbiz/modal/JSelectMaterialModal.vue'
import { getAction, postAction } from '@/api/manage'
import { getMaterialByBatchNumber } from '@/api/api'
import { newTableMixin } from '@/mixins/newTableMixin'
import { Modal } from 'ant-design-vue'

// import { JeecgListMixin } from '@/mixins/JeecgListMixin'
// import { Form } from 'ant-design-vue'
// const useForm = Form.useForm
export default {
  components: { editForm, JSelectMaterialModal },
  mixins: [newTableMixin],
  props: {
    rules: {
      type: Object,
      default: () => {
        return {}
      },
    },

    stockVisible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '新增',
    },
    spinnerList: {
      type: Array,
      default: () => [],
    },
    deoptData: {
      type: Array,
      default: () => [],
    },
    taskId: {
      type: String,
      default: '',
    },
    openType: {
      type: String,
      default: 'add',
    },
  },
  data() {
    return {
      width: '1600px',
      visible: false,
      confirmLoading: false,
      prefixNo: '',
      loading: false,
      dataSource: [],
      columns: table.checkGoodsColumns,
      url: {
        add: '/stocktaking/add',
        update: '/stocktaking/detailUpdate',
        edit: '/stocktaking/itemUpdate',
        updateStock: '/stocktaking/taskUpdateStock/',
        taskCom: '	/stocktaking/taskComplete/',
        detail: '/stocktaking/detail/',
      },
      form: {},
      isShow: false,
      stockType: 'check',
      queryParam: { categoryId: '', materialName: '', batchNumber: '', position: '', isDifference: null },
      isDifferenceData: [
        {
          label: '是',
          value: '1',
        },
        {
          label: '否',
          value: '2',
        },
      ],
      categoryTree: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      editForm: {},
      editVisible: false,
      editFormRules:{
        newInventory:[
          { required: true, message: '请输入实际库存' },
          { pattern: /^[0-9]*$/, message: '只能输入数字' }
        ]
      }
    }
  },
  watch: {
    stockVisible(val) {
      this.loadCategoryTreeData()
      if (val) {
        if (this.taskId) {
          this.$nextTick(() => {
            this.getDetailList(this.taskId)
          })

          return
        }
      } else {
        this.dataSource = []
        this.ipagination.current = 1
        this.loading = false
      }
    },
    editVisible(val) {
      if (!val) {
        this.editForm = {}
        // this.form.resetFields()
      }
    },
  },
  computed: {
    isShowBtn() {
      console.log('==================', this.form.taskStatus)

      if (this.openType === 'detail') return false
      if (this.form.taskStatus !== 1) return false

      return true
    },
  },
  methods: {
    handleEdit(data) {
      this.editForm = { ...data }
      this.editVisible = true
      this.handleChangeNewInventory(data.newInventory)
    },
    onSubmitGoods() {
      this.$refs.editFormModel.validate((valid) => {
        if (valid) {
          postAction(this.url.edit, this.editForm).then((res) => {
            this.$message.success('操作成功')
            this.editVisible = false
          })
        } else {
          return false
        }
      })
    },
    loadCategoryTreeData() {
      let params = {}
      params.id = ''
      queryMaterialCategoryTreeList(params).then((res) => {
        if (res) {
          this.categoryTree = []
          for (let i = 0; i < res.length; i++) {
            let temp = res[i]
            this.categoryTree.push(temp)
          }
        }
      })
    },
    handleCancel() {
      this.$emit('update:stockVisible', false)
    },
    //更新盘点数据
    handleUpdate() {
      let that = this
      const url = this.url.updateStock + this.taskId

      Modal.confirm({
        title: '是否确定更新盘点数据，确定后商品库存将按照当前的盘点数据进行更新',
        onOk() {
          getAction(url)
            .then((res) => {
              that.$message.success('操作成功')
              that.handleCancel()
            })
            .catch((err) => {
              this.$message.error('操作失败')
            })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    handleOk() {
      getAction(this.url.taskCom + this.taskId)
        .then((res) => {
          this.$message.success('操作成功')
        })
        .catch((err) => {
          this.$message.error('操作失败')
        })
      this.handleCancel()
    },
    onChangeGoods() {
      this.$refs.selectModal.queryParam.depotId = this.form.depotId
      this.$refs.selectModal.showModal()
    },
    getDetailList(id) {
      const url = this.url.detail + id
      const form = this.$refs['editForm'].form

      getAction(url).then((res) => {
        const {
          depotId,
          taskName,
          taskStatus,
          taskType,
          createTime,
          createByName,
          materialCount,
          positionRange,
          creator,
          id,
          operBy,
          operTime,
        } = res.data
        form.setFieldsValue({
          depotId,
          taskName,
          taskStatus,
          taskType,
          createTime,
          createByName,
          materialCount,
          positionRange,
          creator,
          id,
          operBy,
          operTime,
        })
        this.getList(id)
      })
    },
    getList(id) {
      const url2 = '/stocktaking/detailByItemList'
      const form = this.$refs['editForm'].form

      const params = { ...this.queryParam, taskStocktakingId: id || this.taskId }
      const url = url2 + '?pageNum=' + this.ipagination.current + '&pageSize=' + this.ipagination.pageSize
      postAction(url, params).then((res) => {
        this.dataSource = res.data
        this.ipagination.total = this.dataSource.length
        const materialExtendIdList = this.dataSource.map((item) => item.batchNumber)

        form.setFieldsValue({
          materialExtendIdList,
        })
        this.getForm(form.getFieldsValue())
      })
    },
    getGoods(rows, ids) {
      const str = ids
        .split(',')
        .filter((item) => item)
        .join(',')
      this.getBatchData(str)
    },
    findAllSelect() {
      const params = { ...this.$refs.selectModal.queryParam }
      getAction('/material/findBatchNumbersBySelect', params).then((res) => {
        this.$refs.selectModal.close()
        this.getBatchData(res.data)
      })
    },
    getBatchData(val) {
      const batchStr = val
        .split(',')
        .filter((item) => item)
        .join(',')
      const params = {
        batchNumber: batchStr,
        organId: '',
        mpList: '',
        prefixNo: '',
      }
      getMaterialByBatchNumber(params).then((res) => {
        this.dataSource.push(...res.data)
        this.dataSource = this.dataSource.reduce((acc, cur) => {
          const hasDuplicate = acc.some((item) => item.batchNumber === cur.batchNumber)
          if (!hasDuplicate) {
            acc.push(cur)
          }
          return acc
        }, [])
      })
    },
    getForm(val) {
      this.form = val
      this.$refs['editForm'].model = val
    },
    //删除
    handleDelete(record) {
      this.dataSource = this.dataSource.filter((item) => item.batchNumber !== record.batchNumber)
    },

    onClearList(val) {
      this.dataSource = []
      this.getForm(val)
      if (val.taskType === 1) {
        this.findAllSelect()
      }
    },

    handleChangeNewInventory(val){
      const inventory = this.editForm.inventory? Number(this.editForm.inventory):0
      this.editForm.differenceCount = val - inventory
    }
  },
}
</script>

<style>
.red-num{
  color: #f5222d;
}
</style>
