<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="ipagination.total"
          :openType="openType"
          :stockType="stockType"
          @changeForm="handleChangeForm"
        ></edit-form>
        <div>
          <a-button v-if="form.taskType === 2" style="margin-bottom: 6px" type="primary" @click="onChangeGoods"
            >选择商品</a-button
          >
          <a-table
            v-if="dataSource.length"
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :scroll="{ x: 'max-content'}"
            :columns="columns"
            :dataSource="dataSource"
            :loading="loading"
            :pagination="ipagination"
            @change="handleTableChange"
          >
            <span v-if="isShowBtn" slot="action" slot-scope="text, record">
              <!-- <a-divider type="vertical" /> -->
              <a-popconfirm @confirm="handleDelete(record)" title="确定删除吗?">
                <a v-if="form.taskType!=1">删除</a>
              </a-popconfirm>
            </span>
            <template slot="inventory" slot-scope="value, record">
              {{ parseInt(value) }}
            </template>
            <!-- <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="handleOk" 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>
  </div>
</template>

<script>
import editForm from './editForm.vue'
import table from '../utils/table'
import JSelectMaterialModal from '../../../components/jeecgbiz/modal/JSelectMaterialModal2.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.goodsColums,
      url: {
        add: '/stocktaking/add',
        update: '/stocktaking/detailUpdate',
      },
      form: {},
      isShow: false,
      stockType: 'task',
      batchNumberStr: ''
    }
  },
  watch: {
    stockVisible(val) {
      if (val) {
        if (this.taskId) {
          this.$nextTick(() => {
            this.getList(this.taskId)
          })

          return
        }
      } else {
        this.dataSource = []
        this.ipagination.current = 1
        this.loading = false
      }
    },
  },
  computed: {
    isShowBtn() {
      if (this.openType === 'add') return true

      if (this.openType === 'detail') return false
      if (this.form.taskStatus !== 1) return false
      return true
    },
  },
  methods: {
    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) => {
            if (res.code === 200) {
              this.$message.success('操作成功')
              this.handleCancel()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    onChangeGoods() {
      if(!this.form.depotId){
        this.$message.warning('请选择仓库！')
        return
      }
      // this.$refs.selectModal.queryParam.depotId = this.form.depotId
      this.$refs.selectModal.showModal()
    },
    getList(id) {
      const url = '/stocktaking/detail/' + id
      const url2 = '/stocktaking/detailByItemList'
      const form = this.$refs['editForm'].form

      getAction(url).then((res) => {
        const {
          depotId,
          taskName,
          taskStatus,
          taskType,
          createTime,
          createByName,
          materialCount,
          positionRange,
          creator,
          id,
          number
        } = res.data
        form.setFieldsValue({
          depotId,
          taskName,
          taskStatus,
          taskType,
          createTime,
          createByName,
          materialCount,
          positionRange,
          creator,
          id,
          number
        })

        postAction(url2, { taskStocktakingId: id }).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())
          console.log('this.dataSource',this.dataSource)
          console.log('this.columns',this.columns)
        })
      })
    },
    getGoods(rows, ids) {
      const str = ids
        .split(',')
        .filter((item) => item)
        .join(',')
      if(!this.form.depotId){
        this.$message.warning('请选择仓库！')
        return
      }
      getAction('/materialBatch/findBatchNumbersByBarCode',{
        barCodes: str,
        depotId:this.form.depotId
      }).then((res) => {
        const batchStr = res.data.split(',')
        .filter((item) => item)
        .join(',')
        this.batchNumberStr = batchStr
        this.getBatchData()
      })
    },
    findAllSelect() {
      if(!this.form.depotId){
        this.$message.warning('请选择仓库！')
        return
      }
      getAction('/materialBatch/findBatchNumbersByBarCode',{
        depotId:this.form.depotId
      }).then((res) => {
        this.$refs.selectModal.close()
        const batchStr = res.data.split(',')
        .filter((item) => item)
        .join(',')
        this.batchNumberStr = batchStr
        this.getBatchData()
      })
    },
    getBatchData() {
      const params = {
        batchNumber: this.batchNumberStr,
        // organId: '',
        // mpList: '',
        // prefixNo: '',
      }
      getAction(`/material/getMaterialByBatchNumber?currentPage=${this.ipagination.current}&pageSize=${this.ipagination.pageSize}`, params).then((res) => {
        this.dataSource = res.data.rows
        if(this.dataSource.length===0){
          this.$message.warning('暂无数据！')
        }
        this.ipagination.total = Number(res.data.total)
        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)
    },

    handleChangeForm(val) {
      this.dataSource = []
      this.ipagination.current = 1
      this.ipagination.total = 0
      this.getForm(val)
      if (val.taskType === 1) {
        this.findAllSelect()
      }
    },

    handleDrag() {},
    // ipagination() {},

    handleTableChange(pagination) {
      if (pagination && pagination.current) {
        this.ipagination = pagination
      }
      if(this.openType=='add'){
        this.getBatchData()
      }else{
        this.getList(this.taskId)
      }
    },
  },
}
</script>

<style></style>
