<template>
  <ele-modal custom-class="ele-dialog-form long-dialog-form" :centered="true" :append-to-body="true"
    :visible.sync="visible" :close-on-click-modal="false" width="60%" @close="cancel" :title="title"
    :fullscreen="fullscreen">
    <template slot="title">
      <modalTitle :title="title" @setFullscreen="fullscreen = !fullscreen">
      </modalTitle>
    </template>
    <headerTitle title="基本信息"></headerTitle>
    <el-form label-width="120px" ref="form" :model="form" :rules="rules" class="el-form-box">
      <el-row>
        <el-col :span="8">
          <el-form-item label="商品名称：" prop="goodsName">
            <el-input placeholder="请输入" v-model="form.goodsName" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品分类：" prop="categoryLevelId">
            <SelectTree :data="gList" placeholder="请选择商品分类" v-model="form.categoryLevelId" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商机编码：" prop="goodsCode">
            <el-input disabled="true" v-model="form.goodsCode" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="商品图片：">
            <ImgUpload ref="imgUploadRef" v-model="form.backgroundImgs" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="产品名称：" prop="productName">
            <el-input disabled="true" v-model="form.productName" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品类型：" prop="productCategoryName">
            <el-input disabled="true" v-model="form.productCategoryName" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品编码：" prop="productCode">
            <el-input disabled="true" v-model="form.productCode" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="属性类型：" prop="produceType">
            <el-input disabled="true" v-model="form.produceType" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="仓库名称：" prop="warehouseId">
            <el-select
            v-model="form.warehouseId"
            placeholder="请选择"
            width="100%"
            @change="warehouseChange"
          >
            <el-option
              v-for="item in form.warehouseList"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            >
            </el-option>
          </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库存：" prop="warehouseNum">
            <el-input disabled="true" v-model="form.warehouseNum" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计量单位：" prop="measuringUnit">
            <el-input disabled="true" v-model="form.measuringUnit" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="重量单位：" prop="weightUnit">
            <el-input disabled="true" v-model="form.weightUnit" maxlength="50"></el-input>
          </el-form-item>
        </el-col> -->
      </el-row>
      <BIZproductList
      ref="BIZproductListRef"
      classType="1"
      :isGetInventoryTotal="true"
      @changeParent="changeParentBiz"
    ></BIZproductList>
    </el-form>
    <headerTitle title="产品" v-show="!isUpdate"></headerTitle>
    <el-form v-show="!isUpdate" label-width="120px" class="el-form-box">
      <el-button
        size="small"
        type="primary"
        icon="el-icon-plus"
        class="ele-btn-icon"
        @click="handParent()"
      >
        选择产品
      </el-button>
      <el-row>
        <el-col :span="8">
          <el-form-item label="产品名称：" >
            <el-input disabled="true" v-model="form.productName" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品类型：">
            <el-input disabled="true" v-model="form.productCategoryName" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品编码：">
            <el-input disabled="true" v-model="form.productCode" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="属性类型：">
            <el-input disabled="true" v-model="form.produceType" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="仓库名称：">
            <el-select
            v-model="form.warehouseId"
            placeholder="请选择"
            width="100%"
            @change="warehouseChange"
          >
            <el-option
              v-for="item in form.warehouseList"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            >
            </el-option>
          </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库存：">
            <el-input disabled="true" v-model="form.warehouseNum" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计量单位：">
            <el-input disabled="true" v-model="form.measuringUnit" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="重量单位：">
            <el-input disabled="true" v-model="form.weightUnit" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <BIZproductList
      ref="BIZproductListRef"
      classType="1"
      :isGetInventoryTotal="true"
      @changeParent="changeParentBiz"
    ></BIZproductList>
    </el-form>
    <headerTitle title="价格"></headerTitle>
    <ProductTable ref="inventoryTable" />
    <template slot="footer">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="cancel">返回</el-button>
    </template>
    
  </ele-modal>
</template>
<script>
import BIZproductList from '@/BIZComponents/product-list.vue';
import SelectTree from './selectTree.vue';
import modalTitle from '@/BIZComponents/modalTitle.vue';
import dictMixins from '@/mixins/dictMixins';
import ProductTable from './productTable.vue';
import { saveGoods } from '@/api/goodsManage/index';
import { getTreeByPid, getPcTreeByPids } from '@/api/classifyManage';
import { getByCode } from '@/api/system/dictionary-data';
import { copyObj } from '@/utils/util';
import {
  getWarehouseOutStock,
  getIdWarehouseList
} from '@/api/saleManage/saleorder';
import { lbjtList } from '@/enum/dict.js';
import { getCode } from '@/api/login/index';
import ImgUpload from './imgUpload.vue';
import { getGoodsById, updateGoods } from '@/api/goodsManage/index'


export default {
  components: {
    ProductTable,
    modalTitle,
    SelectTree,
    BIZproductList,
    ImgUpload
  },
  mixins: [dictMixins],
  data() {
    const formDef = {
      id: '',//商品id
      categoryLevelId: '',//商品分类
      goodsName:'',//商品名称
      goodsCode:'',//商品编码
      backgroundImgs: "",//商品图片
      categoryId: '',//产品id
      productName: '',//产品名称
      productCategoryName: '',//产品类型
      productCode: '',//产品编码
      produceType: '',//属性类型
      warehouseId: '',//仓库名称
      warehouseNum:'',//库存
      measuringUnit: '',//计量单位
      weightUnit: '',//重量单位
      warehouseList:[],//仓库
      imagesFileIds: '',
      children:[],//价格数组
    };
    return {
      // form:{
      //   id: '',//产品id
      //   productName: '',//产品名称
      //   productCategoryName: '',//产品类型
      //   productCode: '',//产品编码
      //   produceType: '',//属性类型
      //   warehouseId: '',//仓库名称
      //   warehouseNum:'',//库存
      //   measuringUnit: '',//计量单位
      //   weightUnit: '',//重量单位
      //   warehouseList:[],//仓库
      // },
      title: '',
      visible: false,
      fullscreen: false,
      form: copyObj(formDef),
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      gList: [], //商品分类
      rules: {
        categoryLevelId: [
            { required: true, message: '请选择商品分类', trigger: 'change' }
          ],
          goodsName: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          goodsCode: [
            { required: true, message: '请输入商品编码', trigger: 'blur' }
          ],
      }
    };
  },

  created() {
    this.getTreeData();
    this.getByCode('goods_price_type'); //获取商品类型字典
  },
  methods: {
    //打开弹出框
    async open(type, row, contactCategoryId) {
      // this.$refs.inventoryTable.resetTable()
      this.form.categoryLevelId = contactCategoryId;
      this.title = type === 'add' ? '新增' : '修改';
      this.visible = true;
      if (type == 'add') {
        this.isUpdate = false;
      } else {
        this.isUpdate = true;
      }
      if (type === 'editGoodsInfo') {
        this.getGoodsById(row.id);
      }
    },

    //获取详情数据
    async getGoodsById(id) {
      let res = await getGoodsById(id);
      this.form = res;
      let goodsImgItem = {id: res.imagesFileIds,url:window.location.origin + '/api/main/file/getFile?objectName=' + res.imagesPaths,status: 'done'}
      this.form.backgroundImgs = goodsImgItem;
      this.$refs.imgUploadRef.putValue(goodsImgItem);
      this.$refs.inventoryTable.putTableList(res.children);
    },

    //查询商品分类
    async getTreeData() {
      const res = await getTreeByPid('1789827921908150274');
      if (res?.code === '0') {
        this.gList = res.data;
      }
    },

    //查询商品价格字典
    async getByCode(code) {
      const res = await getByCode(code);
      if (res?.code === '0') {
        this.goodsTypeList = res.data;
      }
    },

    //库存计算
    async warehouseChange(e) {
      const warehouseOutStock = await getWarehouseOutStock({
        warehouseId: e,
        code: this.form.productCode
      });
      this.form.warehouseNum = warehouseOutStock || 0
    },

    //选择产品
    handParent() {
      this.$refs.BIZproductListRef.open('', 1);
    },

    changeParentBiz(obj = [], idx) {
      this.getGoodsCode('goods_code')
      obj.forEach(async (item, index) => {
        this.form.categoryId = item.id;
        this.form.productName = item.name
        this.form.productCategoryName = item.categoryLevelPath;
        this.form.productCode = item.code;
        this.form.produceType = lbjtList[item.componentAttribute].toString();
        this.form.warehouseId = item.warehouseId;
        this.form.measuringUnit = item.measuringUnit;
        this.form.weightUnit = item.weightUnit;
        this.form.warehouseList = await getIdWarehouseList({ categoryId: item.id });
      })
    },

    //提交
    async save() {
      try {
        if (this.form.categoryId === '' && this.$message.error('请选择产品')) return;
        await this.getValidate();
        // 表单验证通过，执行保存操作
        let commitData = this.$refs?.inventoryTable?.getTableValue() || [];
        if (commitData.length < 1) {
          return
        }
        let comitDatasource = {};
        const {  categoryLevelId, goodsName, goodsCode, categoryId, backgroundImgs, id } = this.form;
        comitDatasource['categoryId'] = categoryId;
        comitDatasource['categoryLevelId'] = categoryLevelId;
        comitDatasource['goodsCode'] = goodsCode;
        comitDatasource['goodsName'] = goodsName;
        comitDatasource['imagesFileIds'] = backgroundImgs[0]?.id;
        comitDatasource['priceList'] = commitData;
        console.log('comitDatasource',comitDatasource);
        this.loading = true;
        var res = {}
        if (!this.isUpdate) {
          res = await saveGoods(comitDatasource);
        } else {
          comitDatasource['id'] = id
          res = await updateGoods(comitDatasource);
        }
        if (res?.code === '0') {
          this.$message.success('操作成功');
          this.cancel();
          this.$emit('done');
        }
      } catch (error) {
        this.loading = false;
      }
    },

    //查询商品编码
    async getGoodsCode(code) {
      this.form.goodsCode = await getCode(code);
    },

    cancel() {
      this.$nextTick(() => {
        this.$refs.inventoryTable.putTableList([]);
        this.$refs.imgUploadRef.putValue();
        // 重置表单验证状态
        // 关闭后，销毁所有的表单数据
        this.form = {}
        this.visible = false;
      });
    },

    getValidate() {
      //开始表单校验
      return Promise.all([
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          }),
          new Promise((resolve, reject) => {
            this.$refs.inventoryTable.validateForm((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          }),
          
        ]);
    }
  }
};
</script>
<style lang="scss" scoped>
.el-form-item {
    margin-bottom: 20px !important;
  }

  .el-form-item__error {
  display: block !important;
  color: red;
  padding-top: 4px;
}
</style>