<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="queryParams" 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="queryParams.categoryId" /> -->
                    <a-tree-select
                      style="width: 100%"
                      :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                      allow-clear
                      :treeData="categoryTree"
                      v-model="queryParams.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="queryParams.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="queryParams.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="queryParams.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="getList">查询</a-button>
                    <a-button style="margin-left: 8px" @click="getList">重置</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="customName" slot-scope="text, record">
          {{ record.name }}
          <a-tag v-if="record.enableSerialNumber == 1" color="orange">序</a-tag>
          <a-tag v-if="record.enableBatchNumber == 1" color="orange">批</a-tag>
        </template> -->
          </a-table>
        </div>
      </a-spin>
      <template slot="footer">
        <a-button @click="handleCancel">取消</a-button>
        <a-button v-if="isShowBtn" @click="handleCancel">完成盘点</a-button>
        <a-button v-if="isShowBtn" @click="handleOk" type="primary">确认更新盘点数据</a-button>
      </template>
    </a-modal>
    <j-select-material-modal
      @ok="getGoods"
      @all="findAllSelect"
      ref="selectModal"
      :multi="true"
    ></j-select-material-modal>
    <a-modal @cancel="editVisible = false" @ok="onSubmitGoods" :visible="editVisible" title="编辑" width="50%">
      <a-form :form="editForm">
        <a-form-item label="盘点任务名称" :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }">
          <a-input disabled v-model="editForm.name" placeholder="请输入"></a-input>
        </a-form-item>
        <a-form-item label="批次号" :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }">
          <a-input disabled v-model="editForm.batchNumber" placeholder="请输入"></a-input>
        </a-form-item>
        <a-form-item label="实际库存" :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }">
          <a-input v-model="editForm.newInventory" placeholder="请输入"></a-input>
        </a-form-item>
        <a-form-item label="实际仓位货架" :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }">
          <a-input v-model="editForm.newPosition" placeholder="请输入"></a-input>
        </a-form-item>
        <a-form-item label="差异数量" :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }">
          <a-input v-model="editForm.differenceCount" placeholder="请输入"></a-input>
        </a-form-item>
        <a-form-item label="差异原因" :labelCol="{ span: 4 }" :wrapperCol="{ span: 14 }">
          <a-input v-model="editForm.differenceReason" placeholder="请输入"></a-input>
        </a-form-item>
      </a-form>
    </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 { 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',
      },
      form: {},
      isShow: false,
      stockType: 'check',
      queryParams: { 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,
    }
  },
  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() {
      return this.openType !== 'detail' || this.form.taskStatus !== 1
    },
  },
  methods: {
    handleEdit(data) {
      this.editForm = { ...data }
      this.editVisible = true
    },
    onSubmitGoods() {
      postAction(this.url.edit, this.editForm).then((res) => {
        this.$message.success('操作成功')
        this.editVisible = 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)
    },
    handleOk() {
      this.$refs.editForm.form.validateFields((err, values) => {
        if (!err) {
          const params = { ...values }
          if (params.taskType === 2) {
            params.materialExtendIdList = this.dataSource.map((item) => item.batchNumber)
          }
          const url = this.openType === 'add' ? this.url.add : this.url.update
          postAction(url, params).then((res) => {
            this.$message.success('操作成功')
            this.handleCancel()
          })
        }
      })
    },
    onChangeGoods() {
      this.$refs.selectModal.queryParam.depotId = this.form.depotId
      this.$refs.selectModal.showModal()
    },
    getDetailList(id) {
      const url = '/stocktaking/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 params = { ...this.queryParams, taskStocktakingId: id }
      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()
      }
    },
  },
}
</script>

<style></style>
