<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="requireDepartmentId">
                <treeselect class="filter-item" default-expand-all v-model="dataForm.requireDepartmentId" :options="deptOptions"
                :normalizer="normalizer" placeholder="出库部门" style="width: 200px" :disabled="type === 'detail'"/>
            </el-form-item>
            <el-form-item label="门店" prop="storeId">
                <el-select v-model="dataForm.storeId" clearable placeholder="请选择" style="width: 200px;" :disabled="type === 'detail'">
                    <el-option :key="item.id" v-for="item in storeList" :label="item.storeName" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="仓库" prop="warehouseId">
                <el-select v-model="dataForm.warehouseId" clearable 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="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>
            <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.inventoryOutInfos" 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="'inventoryOutInfos.'+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" placeholder="入库数量"></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">
                <el-form-item v-if="type !== 'detail'" :prop="'inventoryOutInfos.'+scope.$index+'.sellPrice'"
                    :rules="{ required: true, pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,2})?$/, message: '请输入合法的金额数字，最多两位小数',trigger: 'blur' }" class="tableFormItem">
                    <el-input v-model="scope.row.sellPrice" size="small" placeholder="金额"></el-input>
                  </el-form-item>
                <span v-else>{{ scope.row.sellPrice.toFixed(2) }}</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 v-if="type !== 'detail'" :maxlength="99" v-model="scope.row.remarks"/>
                <span v-else>{{ scope.row.remarks }}</span>
              </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.inventoryOutInfos.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 { createRetrieval, updateRetrieval, readRetrieval } from "@/api/retrieval";
import { storeList } from "@/api/store";
import { warehouseList } from "@/api/warehouse";
import { listDept } from "@/api/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import waves from "@/directive/waves"; // 水波纹指令

export default {
    components: { Treeselect },
    directives: { waves },
    data() {
        return {
            // 树选项
            deptOptions: [],
            recipientsList:[],
            storeList: [],
            warehouseList: [],
            id: '',
            type: '',
            /** 表单*/
            dataForm: {
                serialDate:'',
                requireDepartmentId:undefined,
                storeId:undefined,
                warehouseId:undefined,
                remarks:undefined,
                inventoryOutInfos: []
            },
            rules: {
                serialDate: [
                    { required: true, message: '请选择出库时间', trigger: 'blur' }
                ],
                requireDepartmentId: [
                    { required: true, message: '请选择出库部门', trigger: 'blur' }
                ],
                warehouseId: [
                    { required: true, message: '请选择仓库', trigger: 'blur' }
                ],
            },
        }
    },
    watch: {
        $route: {
            immediate: true,
            handler(newVal) {
                if (this.$route.name === 'retrievalAdd') {
                    this.dataForm = {
                        serialDate:undefined,
                        storeId:undefined,
                        warehouseId:undefined,
                        addHandlerId:undefined,
                        fileIds:undefined,
                        fileList: [],
                        inventoryOutInfos: []
                    }
                } else if (this.$route.name === 'retrievalDetail') {
                    this.type = 'detail'
                }
                if (this.$route.params.id) {
                    this.id = this.$route.params.id
                    this.getDataFormDetail()
                }
            }
        }
    },
    mounted() {
        this.getStoreList();
        this.getWarehouseList(); 
        this.getListDept();
    },
    methods: {
        getListDept() {
            listDept().then(response => {
                this.deptOptions = this.handleTree(response.data.data, "deptId");
            });
        },
        /** 转换部门数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.deptId,
                label: node.deptName,
                children: node.children
            };
        },
        /** 获取门店列表数据 */
        getStoreList(){
            storeList().then(response => {
                this.storeList = response.data.data;
            }).catch(() => { });
        },
        /** 获取仓库列表数据 */
        getWarehouseList() {
            warehouseList().then(response => {
                this.warehouseList = response.data.data;
            }).catch(() => {});
        },
        /** 获取详情页面数据 */
        getDataFormDetail() {
            readRetrieval({ id: this.id }).then(response => {
                let dataForm = response.data.data;
                dataForm.inventoryOutInfos = dataForm.inventoryOutInfos == null ? [] : dataForm.inventoryOutInfos
                dataForm.inventoryOutInfos = dataForm.inventoryOutInfos == null ? [] : dataForm.inventoryOutInfos
                this.dataForm = dataForm;
            }).catch(() => {})
        },
         // 选择商品
        async handleSelectGoods() {
            if (!this.dataForm.warehouseId) {
                this.$message.error('请先选择仓库！')
                return
            }else{
                console.log(this.dataForm.inventoryOutInfos)
                let selectedIds = this.dataForm.inventoryOutInfos.map(item => item.productId);
                const Goods = await this.$EnPickerGoods({
                    // goodsApi: '/warehouse-entry/info/inventory',
                    selectedIds: selectedIds,
                    goodsApiParams: { warehouseId: this.dataForm.warehouseId, type:'2' }
                })
                if (!Goods.length) return
                const inventoryOutInfos = Goods.map(item => {
                    item.updateNumber = 1
                    item.sumPrice = item.createPrice * 1
                    return item
                })
                this.dataForm.inventoryOutInfos = this.dataForm.inventoryOutInfos && this.dataForm.inventoryOutInfos.length ? this.dataForm.inventoryOutInfos.concat(inventoryOutInfos) : this.dataForm.inventoryOutInfos = inventoryOutInfos
            }
            
        },
        submitForm(){
            this.$refs["dataForm"].validate((valid) => {
                if (valid) {
                    if(this.dataForm.inventoryOutInfos.length == 0){
                        this.$message.error('请选择商品/物料！')
                        return
                    }else{
                        if(this.id){
                            updateRetrieval(this.dataForm).then(() => {
                                this.$notify({
                                    title: '成功',
                                    message: '更新成功',
                                    type: 'success',
                                    duration: 2000
                                })
                                this.roBack();
                            })
                        }else{
                            createRetrieval(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() {
            // const { callback } = this.$route.params
            // if (typeof callback === 'function') callback()
            this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
                const latestView = views.slice(-1)[0]
                if (latestView) {
                    this.$router.push(latestView.path)
                } else {
                    this.$router.push('/')
                }
            })
            // this.$router.push({ name: 'retrieval' })
        },
    }
}
</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>