<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"
    :maxable="true"
    :resizable="true"
    :title="title"
  >
    <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"
              :disabled="type == 'view'"
            ></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"
              :disabled="type == 'view'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品编码：" prop="goodsCode">
            <el-input
              disabled
              v-model="form.goodsCode"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品级别：" prop="level">
            <el-select
              v-model="form.level"
              placeholder="请选择"
              width="100%"
              :disabled="type == 'view'"
            >
              <el-option
                v-for="item in levelList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装规格：">
            <el-input
              disabled
              v-model="form.packingSpecification"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="商品图片：">
            <ImgUpload
              ref="imgUploadRef"
              v-model="imgs"
              v-if="type != 'view'"
            />
            <el-image
              v-if="type == 'view'&&imgs.length>0"
              style="width: 100px; height: 100px"
              fit="cover"
              :src="imgs[0].url"
              :preview-src-list="imgs.map(item=>item.url)"
            />
          </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
              v-model="form.productName"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物品类型：">
            <el-input
              disabled
              v-model="form.productCategoryName"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物品编码：">
            <el-input
              disabled
              v-model="form.productCode"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="属性类型：">
            <el-input
              disabled
              v-model="form.produceType"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="包装规格：">
            <el-input
              disabled="true"
              v-model="form.packingSpecification"
              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
              v-model="form.warehouseNum"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计量单位：">
            <el-input
              disabled
              v-model="form.measuringUnit"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="重量单位：">
            <el-input
              disabled
              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" :type="type" />
    <template slot="footer">
      <el-button type="primary" @click="save" v-if="type != 'view'">保存</el-button>
      <el-button @click="cancel">返回</el-button>
    </template>
  </ele-modal>
</template>
<script>
  const formDef = {
    id: '', //商品id
    categoryLevelId: '', //商品分类
    goodsName: '', //商品名称
    goodsCode: '', //商品编码
    imagesPaths: '', //商品图片
    imagesFileIds: '', //商品图片id
    categoryId: '', //物品id
    productName: '', //物品名称
    productCategoryName: '', //物品类型
    productCode: '', //物品编码
    produceType: '', //属性类型
    warehouseId: '', //仓库名称
    warehouseNum: '', //库存
    packingSpecification: '', //包装规格
    measuringUnit: '', //计量单位
    weightUnit: '', //重量单位
    warehouseList: [], //仓库
    level: '2',
    children: [] //价格数组
  };
  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';
  import { levelList } from '@/enum/dict.js';
  export default {
    components: {
      ProductTable,
      modalTitle,
      SelectTree,
      BIZproductList,
      ImgUpload
    },
    mixins: [dictMixins],
    data() {
      return {
        imgs: [],
        title: '',
        visible: false,
        type: '',
        fullscreen: false,
        form: copyObj(formDef),
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        gList: [], //商品分类
        levelList,
        rules: {
          categoryLevelId: [
            { required: true, message: '请选择商品分类', trigger: 'change' }
          ],
          goodsName: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          goodsCode: [
            { required: true, message: '请输入商品编码', trigger: 'blur' }
          ],
          level: [
            { required: true, message: '请选择商品级别', trigger: 'blur' }
          ]
        }
      };
    },

    created() {
      this.getTreeData();
    },
    methods: {
      //打开弹出框
      async open(type, row, contactCategoryId) {
        // this.$refs.inventoryTable.resetTable()
        this.form.categoryLevelId = contactCategoryId;
        this.title =
          type === 'add' ? '新增' : type === 'view' ? '详情' : '修改';
        this.type = type;
        this.visible = true;
        if (type == 'add') {
          this.isUpdate = false;
        } else {
          this.isUpdate = true;
        }
        if (type != 'add') {
          this.getGoodsById(row.id);
        }
      },

      //获取详情数据
      async getGoodsById(id) {
        let res = await getGoodsById(id);
        if (res.imagesPaths) {
          res.imagesPaths.split(',').map((item, index) => {
            this.imgs.push({
              id: res.imagesFileIds.split(',')[index],
              url:
                window.location.origin +
                '/api/main/file/getFile?objectName=' +
                item,
              status: 'done'
            });
          });
        }
        console.log(this.imgs, 'this.imgs');
        this.form = res;
        this.$refs.imgUploadRef?.putValue(this.imgs);
        this.$refs.inventoryTable?.putTableList(res.goodsPriceList);
      },

      //查询商品分类
      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.packingSpecification = item.extField?.packingSpecification;
          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() {
        //  console.log(this.form.imagesPaths)
        //   return
        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,
            id,
            level,
            packingSpecification
          } = this.form;
          comitDatasource['categoryId'] = categoryId;
          comitDatasource['categoryLevelId'] = categoryLevelId;
          comitDatasource['goodsCode'] = goodsCode;
          comitDatasource['goodsName'] = goodsName;
          comitDatasource['imagesFileIds'] = this.imgs
            ?.map((item) => item.id)
            .toString();

          comitDatasource['level'] = level;
          comitDatasource['packingSpecification'] = packingSpecification;
          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.imgs = [];
          // 重置表单验证状态
          // 关闭后，销毁所有的表单数据
          (this.form = copyObj(formDef)), (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>
