<template>
    <div class="app-container">
        <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="120px" inline>
            <h3>调拨单</h3>
            <el-form-item label="调拨时间" prop="serialDate">
                <el-date-picker v-model="dataForm.serialDate" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                    placeholder="选择日期时间" style="width:200px" :disabled="type === 'detail'">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="调出仓库" prop="warehouseId">
                <el-select v-model="dataForm.warehouseId" clearable filterable placeholder="请选择" style="width: 200px;" :disabled="type === 'detail'">
                    <el-option :key="item.id" v-for="item in warehouseList" :label="item.warehouseName" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="调出经手人" prop="outHandlerId">
                <el-select v-model="dataForm.outHandlerId" clearable filterable placeholder="请选择" style="width: 200px" :disabled="type === 'detail'">
                    <el-option :key="item.loginId" v-for="item in userSelsctList" :label="item.deptName+'_'+item.userName" :value="item.loginId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="调入仓库" prop="warehouseTargetId">
                <el-select v-model="dataForm.warehouseTargetId" clearable filterable placeholder="请选择" style="width: 200px;" :disabled="type === 'detail'">
                    <el-option :key="item.id" v-for="item in warehouseList" :label="item.warehouseName" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="调入经手人" prop="addHandlerId">
                <el-select v-model="dataForm.addHandlerId" clearable filterable placeholder="请选择" style="width: 200px" :disabled="type === 'detail'">
                    <el-option :key="item.loginId" v-for="item in userSelsctList" :label="item.deptName+'_'+item.userName" :value="item.loginId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remarks">
                <el-input style="width:535px" v-model="dataForm.remarks" :maxlength="120"
                    type="textarea" :disabled="type === 'detail'" :autosize="{ minRows: 1, maxRows: 4 }"
                    placeholder="请输入备注 最大120字"></el-input>
            </el-form-item>
            <el-form-item label="附件" prop="fileIds">
                <el-upload style="width: 200px" :limit="1" :action="fileUrl" :file-list="dataForm.fileList" :on-success="handleFileSuccess"
                    :before-upload="beforeUploadFile" :on-remove="handleRemove">
                    <el-button size="small" type="primary" :disabled="type === 'detail'">点击上传</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item label="作废原因" v-if="dataForm.cancelMsg">
                <el-input style="width:535px" v-model="dataForm.cancelMsg" type="textarea" disabled :autosize="{ minRows: 1, maxRows: 4 }"></el-input>
            </el-form-item>
            <div class="mx">
        <h3>调拨明细</h3>
        <el-button size="small" type="primary" v-if="type !== 'detail'"
          @click="handleSelectGoods" icon="el-icon-plus">商品/物料</el-button>
      </div>
      <el-table size="small" :data="dataForm.inventoryEntryInfos" border :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }" style="width: 100%">
            <el-table-column label="商品编号">
              <template slot-scope="scope">
                {{ scope.row.productCode }}
              </template>
            </el-table-column>
            <el-table-column label="商品名称">
              <template slot-scope="scope">
                {{ scope.row.productName }}
              </template>
            </el-table-column>
            <el-table-column label="单价(￥)">
              <template slot-scope="scope">
                {{ scope.row.createPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="库存数量">
              <template slot-scope="scope">
                {{ scope.row.createProductNumber }}
              </template>
            </el-table-column>
            <el-table-column label="调拨数量">
              <template slot-scope="scope">
                <el-form-item v-if="type !== 'detail'" :prop="'inventoryEntryInfos.'+scope.$index+'.updateNumber'" :rules="{ required: true, message: '调拨数量不能为空', trigger: 'blur' }" class="tableFormItem">
                    <el-input-number v-model="scope.row.updateNumber" @change="handleChange(scope.row)" size="small" :min="1" :max="10000" label="调拨数量"></el-input-number>
                </el-form-item>
                <span v-else>{{ scope.row.updateNumber }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="合计(￥)">
              <template slot-scope="scope">
                {{ scope.row.sumPrice.toFixed(2) }}
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="备注">
              <template slot-scope="scope">
                <el-input :maxlength="99" v-model="scope.row.remark" :disabled="type === 'detail'" />
              </template>
            </el-table-column> -->
            <el-table-column label="操作" width="150" v-if="type !== 'detail'">
              <template slot-scope="scope">
                <el-button size="mini" type="danger"
                  @click="dataForm.inventoryEntryInfos.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <div class="footer">
            <el-button type="primary" @click="submitForm" v-if="type !== 'detail'">保存
            </el-button>
            <el-button @click="roBack()">返回
            </el-button>
        </div>
    </div>
</template>
<script>
import { createRequisition, updateRequisition, readRequisition } from "@/api/requisition";
import { supplierList } from "@/api/supplier";
import { warehouseList } from "@/api/warehouse";
import { allUserList } from "@/api/public";
import waves from "@/directive/waves"; // 水波纹指令

export default {
    directives: { waves },
    data() {
        return {
            fileUrl:this.upLoadUrl,
            userSelsctList:[],
            supplierList: [],
            warehouseList: [],
            id: '',
            type: '',
            /** 表单*/
            dataForm: {
                serialDate:'',
                warehouseId:undefined,
                outHandlerId:undefined,
                warehouseTargetId:undefined,
                addHandlerId:undefined,
                fileIds:undefined,
                fileList: [],
                remarks:undefined,
                inventoryEntryInfos: []
            },
            rules: {
                serialDate: [
                    { required: true, message: '请选择调拨时间', trigger: 'blur' }
                ],
                warehouseId: [
                    { required: true, message: '请选择调出仓库', trigger: 'blur' }
                ],
                outHandlerId: [
                    { required: true, message: '请选择调出经手人', trigger: 'blur' }
                ],
                warehouseTargetId: [
                    { required: true, message: '请选择调入仓库', trigger: 'blur' }
                ],
                addHandlerId: [
                    { required: true, message: '请选择调入经手人', trigger: 'blur' }
                ],
                remarks: [
                    { required: true, message: '请输入备注', trigger: 'blur' }
                ],
            },
        }
    },
    watch: {
        $route: {
            immediate: true,
            handler(newVal) {
                if (this.$route.name === 'requisitionAdd') {
                    this.dataForm = {
                        serialDate:'',
                        warehouseId:undefined,
                        outHandlerId:undefined,
                        warehouseTargetId:undefined,
                        addHandlerId:undefined,
                        fileIds:undefined,
                        fileList: [],
                        remarks:undefined,
                        inventoryEntryInfos: []
                    }
                } else if (this.$route.name === 'requisitionDetail') {
                    this.type = 'detail'
                }
                if (this.$route.params.id) {
                    this.id = this.$route.params.id
                    this.getDataFormDetail()
                }
            }
        }
    },
    mounted() {
        this.getSupplierList();
        this.getStoreList(); 
        this.getAllUserList(); 
    },
    methods: {
        /** 获取供应商列表数据 */
        getSupplierList(){
            supplierList().then(response => {
                this.supplierList = response.data.data;
            }).catch(() => { });
        },
        /** 获取仓库列表数据 */
        getStoreList() {
            warehouseList().then(response => {
                this.warehouseList = response.data.data;
            }).catch(() => {});
        },
        /** 获取人员列表数据 */
        getAllUserList() {
            allUserList().then(response => {
                this.userSelsctList = response.data.data;
            }).catch(() => { });
        },
        /** 获取详情页面数据 */
        getDataFormDetail() {
            readRequisition({ id: this.id }).then(response => {
                let dataForm = response.data.data;
                dataForm.inventoryEntryInfos = dataForm.inventoryEntryInfos == null ? [] : dataForm.inventoryEntryInfos
                dataForm.inventoryOutInfos = dataForm.inventoryOutInfos == null ? [] : dataForm.inventoryOutInfos
                this.dataForm = dataForm;
                this.dataForm.fileList = dataForm.files == null ? [] : dataForm.files;
            }).catch(() => {})
        },
         // 选择商品
        async handleSelectGoods() {
            if (!this.dataForm.warehouseId) {
                this.$message.error('请先选择调出仓库！')
                return
            }else{
                console.log(this.dataForm.inventoryEntryInfos)
                let selectedIds = this.dataForm.inventoryEntryInfos.map(item => item.id);
                const Goods = await this.$EnPickerGoods({
                    // goodsApi: '/warehouse-entry/info/inventory',
                    selectedIds: selectedIds,
                    goodsApiParams: { warehouseId: this.dataForm.warehouseId, type:'2' }
                })
                if (!Goods.length) return
                const inventoryEntryInfos = Goods.map(item => {
                    item.updateNumber = 1
                    item.sumPrice = item.createPrice * 1
                    return item
                })
                this.dataForm.inventoryEntryInfos = this.dataForm.inventoryEntryInfos && this.dataForm.inventoryEntryInfos.length ? this.dataForm.inventoryEntryInfos.concat(inventoryEntryInfos) : this.dataForm.inventoryEntryInfos = inventoryEntryInfos
            }
            
        },
        submitForm(){
            this.$refs["dataForm"].validate((valid) => {
                if (valid) {
                    if(this.dataForm.inventoryEntryInfos.length == 0){
                        this.$message.error('请选择商品/物料！')
                        return
                    }else{
                        if(this.id){
                            updateRequisition(this.dataForm).then(() => {
                                this.$notify({
                                    title: '成功',
                                    message: '更新成功',
                                    type: 'success',
                                    duration: 2000
                                })
                                this.roBack();
                            })
                        }else{
                            createRequisition(this.dataForm).then(() => {
                                this.$notify({
                                    title: "成功",
                                    message: "创建成功",
                                    type: "success",
                                    duration: 2000,
                                });
                                this.roBack();
                            })
                        }
                    }   
                }
            });
        },
        handleChange(row) {
            if (row.createPrice && row.updateNumber) {
                row.sumPrice = row.createPrice * row.updateNumber
            }
        },
        roBack() {
            this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
                this.$router.push({ name: 'requisition' })
            })
        },
        handleRemove(file, fileList) {
        console.log(file, fileList);
        let fileIds = [];
        for (let i in fileList) {
            let id = fileList[i].response.data.id;
            fileIds.push(id);
        }
        this.dataForm.fileIds = fileIds.join(",");
        },
        beforeUploadFile(file) {
        console.log(file);
        const size = file.size / 1024 / 1024;
        console.log(size);
        if (size > 10) {
            this.$message.error("文件大小不能超过10MB！");
            return false;
        }
        },
        handleFileSuccess(res, file, fileList) {
        console.log(file, fileList);
        console.log("------", "==========");
        console.log("res = ", res);

        let fileIds = [];
        for (let i in fileList) {
            let response = fileList[i].response;
            if (response.errno && response.errno != "0") {
            this.$message.error("该文件上传失败,已被移除,请重新上传!");
            // 上传失败移除该 file 对象
            fileList.splice(i, 1);
            } else {
            let id = fileList[i].response.data.id;
            fileIds.push(id);
            }
        }
        this.dataForm.fileIds = fileIds.join(",");
        },
    }
}
</script>
<style>
/** 底部步骤 */
.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}
.mx {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
/** 表格中输入框样式 */
.tableFormItem {
  width: 100%;
  margin-bottom: 0;
}
</style>