<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!--     卡片头   -->
        <div style="width: 100%;height: 100px;position: relative;">
          <el-form ref="asnFromRes" :model="asnFrom" :rules="rules" size="small" label-width="80px">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="单据类型" prop="billType">
                    <BillTypeSelect v-model="asnFrom.billType" :value-key="'id'" :bill_code="'XBRK'" :immediate="true"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
              <el-form-item label="单号" prop="code">
                <el-input :disabled="true" v-model="asnFrom.code"  style="width: 200px;"/>
              </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="订单数量">
                  <el-input :disabled="true" v-model="asnFrom.orderQuantity"  style="width: 200px;"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="订单日期" prop="orderDate" >
                  <el-date-picker
                    style="width: 200px;"
                    v-model="asnFrom.orderDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="备注:">
                  <el-input v-model="asnFrom.description" placeholder="请输入备注"
                  />
                </el-form-item>
              </el-col>
            </el-row>
                <div style="width: 50%;float: left">
                  <el-button type="primary" :disabled="asnFrom.code != null" @click="submitFromAsn(asnFrom)">提交
                  </el-button>
                </div>
          </el-form>
        </div>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" :tableKey="this.$options.name">
        <!--<el-button
          slot="right"
          class="filter-item"
          type="primary"
          size="mini"
          @click="rkAndQxButtonM(1)"
          :loading="logining1"
        >
          整单上架
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          type="primary"
          size="mini"
          :disabled="crud.selections.length === 0"
          @click="qxshM(crud.selections)"
          :loading="logining3"
        >
          取消上架
        </el-button>-->
        <el-button
          slot="right"
          class="filter-item"
          type="primary"
          size="mini"
          :disabled="crud.selections.length === 0"
          @click="qxshM(crud.selections)"
          :loading="logining3"
        >
          取消收货
        </el-button>
        <el-upload
          class="upload-demo"
          ref="upload"
          slot='right'
          style="float: right;padding-left: 5px"
          :action="baseApi+'/api/importData/importAsnDetail?asnId='+this.asnId"
          :file-list="fileList"
          :on-success=handleSuccess
          :on-error="handleError"
          :headers="headers"
          :show-file-list="true">
          <el-button size="mini" type="success" icon="el-icon-upload">导入</el-button>
        </el-upload>
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                 :title="crud.status.title" width="400px"
      >
        <el-form ref="form" :rules="asnDetailRules" :model="form" size="small" label-width="100px"
                 style="height: 300px"
        >
          <el-form-item label="制造库位" prop="zzkwCode">
            <BomAccountPointSelect v-model="form.point.code" :value-key="'bom_account_id'" @change="getChangeVule" :immediate="true"/>
          </el-form-item>
          <el-form-item label="品番">
            <el-input v-model="form.item.code" />
          </el-form-item>
          <el-form-item label="品名">
            <el-input v-model="form.item.name" />
          </el-form-item>
          <el-form-item label="数量">
            <el-input v-model="form.orderQty" />
          </el-form-item>
          <el-form-item label="税别">
            <el-input v-model="form.propC2"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" :rows="3" type="textarea" style="width: 270px;"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
                @selection-change="crud.selectionChangeHandler" :height="crud.tableHeight"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="item.code" label="品番"/>
        <el-table-column prop="item.name" label="品名"/>
        <el-table-column prop="orderQty" label="订单数量"/>
        <el-table-column prop="receivedQty" label="收货数量"/>
        <el-table-column prop="point.code" label="库位"/>
        <el-table-column prop="propC2" label="税别"/>
        <el-table-column prop="remark" label="备注">
          <template slot-scope="scope">
            <div>{{ scope.row.remark }}</div>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','asnDetail:edit','asnDetail:del'])" label="操作" width="150px"
                         align="center"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination/>
    </el-card>
  </div>
</template>

<script>
import crudAsnDetail, { rkAndQxButton } from '@/api/asnDetail'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation.vue'
import crudOperation from '@crud/CRUD.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import pagination from '@crud/Pagination.vue'
import { queryItemAll } from '@/api/item'
import Search from '@/views/monitor/log/search.vue'
import AsnTask from '@/views/business-asn/asnDetail/viewAsnTask.vue'
import DateRangePicker from '@/components/DateRangePicker/index.vue'
import { getToken } from '@/utils/auth'
import { queryPointList } from '@/api/point'
import { getIdByAsn } from '@/api/asn'
import { getAreas } from '@/api/area'
import { getBillType } from '@/api/billType'
import crudAsn from '@/api/asn'
import { queryBomAccountList } from '@/api/bomAccount'
import {mapGetters} from "vuex";
import PointSelect from "@/views/generic-component/PointSelect.vue";
import BillTypeSelect from "@/views/generic-component/BillTypeSelect.vue";
import ItemSelect from "@/views/generic-component/ItemSelect.vue";
import BomAccountPointSelect from "@/views/generic-component/BomAccountPointSelect.vue";

const defaultForm = {
  id: null,
  asn: null,
  item: {id:null,code:null,name:null},
  bom_account_id: null,
  item_code:null,
  item_name:null,
  item_id:null,
  zzkw_code:null,
  point_id:null,
  stock: null,
  lineNo: null,
  po: null,
  status: 'OPEN',
  point: {id:null,code:null},
  orderQty: 0,
  receivedQty: 0,
  moveQty: 0,
  putQty: 0,
  weight: 0,
  volume: 0,
  remark: null,
  propC1: null,
  propC2: null,
  propC3: null,
  propC4: null,
  propC5: null,
  propC6: null,
  propD1: null,
  propD2: null,
  deptId: null,
  sourceName: null,
  sourceId: null,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null
}
const asnQuery = {
  asnId: 0
}
export default {
  name: 'viewXbDetail',
  components: {
    BomAccountPointSelect,
    ItemSelect,
    BillTypeSelect,
    PointSelect, DateRangePicker, AsnTask, Search, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['asn_status','bonded_type'],
  cruds() {
    return CRUD({
      title: '收货数据',
      url: 'api/asnDetail',
      idField: 'id',
      query: { asnId: 0 },
      sort: 'id,desc',
      crudMethod: { ...crudAsnDetail },
      optShow: {
        add: true,
        edit: false,
        del: true,
        reset: false,
        download: false
      }
    })
  },
  created() {
    //判断是否有数据
    this.crud.query = asnQuery
    let ids = this.$route.query.ids
    if (ids != null) {
      this.crud.query.asnId = ids
      this.asnId = ids
    } else {
      this.crud.query.asnId = 0
      this.asnId = 0
    }
    this.crud.refresh()
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'asnDetail:add'],
        edit: ['admin', 'asnDetail:edit'],
        del: ['admin', 'asnDetail:del']
      },
      rules: {
        cusCode: [
          { required: true, message: '箱单号不能为空', trigger: 'blur' }
        ],
        orderDate: [{
          required: true, message: '订单日期不能为空', trigger: 'blur'
        }],
        billType: [{
          required: true, message: '单据类型不能为空', trigger: 'blur'
        }]
      },
      asnDetailRules: {
        orderQty: [
          { required: true, message: '订单数量不能为空', trigger: 'blur' }
        ]
        // point: [
        //   { required: true, message: '库位不能为空', trigger: 'blur' }
        // ]
      },
      //下拉物料
      itemOptions: [],
      //下拉点位
      pointOptions: [],
      pointOption2: [],
      //下拉库区
      areaOptions: [],
      //下拉类型
      billTypeOptions: [],
      // 新增主表
      asnFrom: {
        id: null,
        code: null,
        area: null,
        status: 'OPEN',
        cusCode: null,
        relatedBill1: null,
        relatedBill2: null,
        relatedBill3: null,
        orderDate: null,
        estimateDate: null,
        receivedDate: null,
        fromName: null,
        fromAddress: null,
        fromMan: null,
        fromTel: null,
        orderQuantity: 0,
        receivedQuantity: 0,
        putawayQuantity: 0,
        vehicle: null,
        billType: null,
        dept: null,
        description: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null
      },
      //主id
      asnId: 0,
      asn: {},
      asnDetailButton: {
        button: 0,
        id: 0,
        oneRNumber: 0,
        oneRPoint: {},
        asnDetailData: {},
        asnDetailDataS: []
      },
      dyrkTf: false,
      logining1: false,
      logining2: false,
      logining3: false,
      pointTF:true,
    }
  },
  // beforeDestroy() {    //页面关闭时清除定时器
  //   clearInterval(this.clearTimeSet);
  // },
  mounted() {

  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.asnTF()
      return true
    },
    setTime() { //设置定时器
      // this.clearTimeSet=setInterval(() => {
      //   this.asnTF();
      // }, 1000*20);
    },
    //获取当前时间
    getNewDate() {
      const date = new Date()
      const year = date.getUTCFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      //存当前时间
      this.asnFrom.orderDate = `${year}-${month}-${day}`
    },
    //过滤重复数据
    filterListObj(listObj) {
      let date = []
      let onOff = true
      listObj.filter((i) => {
        onOff = true
        date.filter((ii) => {
          if (i.id === ii.id) {
            onOff = false
          }
        })
        if (onOff) {
          date.push(i)
        }
      })
      return date
    },
    //判断是否是新增主表和是查看明细新政附表
    asnTF() {
      if (this.asnId != 0) {
        getIdByAsn(this.asnId).then(res => {
          //存储主表的对象
          this.asn = res
          defaultForm.asn = res
          //将主表数据在新增哪里展示
          this.asnFrom = res
          asnQuery.asnId = res.id
          // if (res.area.besh){
          //   this.getPointList(res)
          // }
        })
      } else {
        this.getNewDate()
      }
    },
    //新增主表数据
    submitFromAsn(data) {
      //校验
      this.$refs['asnFromRes'].validate((valid) => {
        if (valid) {
          crudAsn.add(data).then(res => {
            //存主表id
            this.asnId = res.id
            //加载数据
            this.asnTF()
            this.$message.success('添加成功')
            // this.crud.toQuery()
            this.$router.push({ path: '/business-asn/viewXbDetail', query: { ids: res.id } })
          })
        } else {
          return false
        }
      })
    },
    rkAndQxButtonM(num) {
      if (num === 1) {   //整单入库
        this.logining1 = true
        let data = this.asnDetailButton
        data.button = num
        data.id = this.asn.id
        rkAndQxButton(data).then(res => {
          this.$message.success(res)
          this.logining1 = false
          this.crud.toQuery()
        }).catch(e => {
          this.logining1 = false
        })
      } else if (num === 2) {
        this.$refs['formdyrk'].validate((valid) => {
          if (valid) {
            this.logining2 = true
            let data = this.asnDetailButton
            data.button = num
            data.id = this.asn.id
            rkAndQxButton(data).then(res => {
              this.$message.success(res)
              this.dyrkTf = false
              this.logining2 = false
              this.crud.toQuery()
            }).catch(e => {
              this.logining2 = false
            })
          } else {
            // console.log('error submit!!');
            return false
          }
        })
      } else if (num === 3) {
        this.logining3 = true
        let data = this.asnDetailButton
        data.button = num
        data.id = this.asn.id
        rkAndQxButton(data).then(res => {
          this.$message.success(res)
          this.logining3 = false
          this.crud.toQuery()
        }).catch(e => {
          this.logining3 = false
        })
      }
    },
    //单一入库
    dyrkM(data) {
      this.dyrkTf = !this.dyrkTf
      console.log(data[0].item.code)
      this.getPointList(data[0].item.code, this.asn)
      this.asnDetailButton.asnDetailData = data[0]
    },
    //取消收货
    qxshM(data) {
      this.asnDetailButton.asnDetailDataS = data
      this.rkAndQxButtonM(3)
    },
    getChangeVule(dben) {
      this.form.orderQty=dben.srs;
      this.form.item.code=dben.item_code;
      this.form.item.name=dben.item_name;
      this.form.sourceId=dben.bom_account_id
      this.form.item.id=dben.item_id;
      this.form.point.id=dben.zzkw_id;
      this.form.point.code=dben.zzkw_code;
      this.form.propC2=dben.bonded;
    },
    handleSuccess(response, file, fileList) {
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      this.crud.status.add = CRUD.STATUS.NORMAL
      this.crud.resetForm()
      this.crud.toQuery()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    }
  }
}
</script>

<style scoped>

</style>
