<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="openType"
          :stockType="stockType"
          @getForm="getForm"
          @clear="onClearList"
        ></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"
            :columns="columns"
            :dataSource="dataSource"
            :loading="loading"
            :scroll="{ y: 500 }"
            :pagination="false"
            @change="handleTableChange"
          >
            <span v-if="form.taskType === 2" slot="action" slot-scope="text, record">
              <a-divider type="vertical" />
              <a-popconfirm @confirm="handleDelete(record)" title="确定删除吗?">
                <a>删除</a>
              </a-popconfirm>
            </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="handleOk" type="primary">确认发布盘点任务</a-button>
      </template>
    </a-modal>
    <j-select-material-modal
      @ok="getGoods"
      @all="findAllSelect"
      ref="selectModal"
      :multi="true"
    ></j-select-material-modal>
  </div>
</template>

<script>
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.goodsColums,
      url: {
        add: '/stocktaking/add',
        update: '/stocktaking/detailUpdate',
      },
      form: {},
      isShow: false,
      stockType: 'task',
    }
  },
  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) => {
            this.$message.success('操作成功')
            this.handleCancel()
          })
        }
      })
    },
    onChangeGoods() {
      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,
        } = res.data
        form.setFieldsValue({
          depotId,
          taskName,
          taskStatus,
          taskType,
          createTime,
          createByName,
          materialCount,
          positionRange,
          creator,
          id,
        })

        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())
        })
      })
    },
    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()
      }
    },

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

    handleTableChange() {},
  },
}
</script>

<style></style>
