<template>
  <div>
    <el-form :model="value" :rules="rules" ref="productInfoForm" label-width="120px" style="width: 700px" size="small">
      <el-form-item label="商品分类：" prop="productCategoryId">
        <el-cascader
          v-model="selectProductCateValue"
          :placeholder="cascaderPlaceholder"
          :options="productCateOptions">
        </el-cascader>
      </el-form-item>
      <el-form-item label="商品名称：" prop="name">
        <el-input v-model="value.name"></el-input>
      </el-form-item>
      <!-- <el-form-item label="副标题：" prop="subTitle">
        <el-input v-model="value.subTitle"></el-input>
      </el-form-item> -->
      <el-form-item label="商品品牌：" prop="brandId">
        <el-select
        filterable
          v-model="value.brandId"
          @change="handleBrandChange"
          placeholder="请选择品牌">
          <el-option
            v-for="item in brandOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供应商：" prop="compId">
        <el-select
          filterable
          v-model="value.compId"
          @change="handleSupplierChange"
          placeholder="请选择供应商"
        >
          <el-option
            v-for="item in supplierOptList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生产地：" prop="placeOfProductionId">
        <el-select
        filterable
          v-model="value.placeOfProductionId"
          @change="handleOriginChange"
          placeholder="请选择生产地">
          <el-option
            v-for="item in originOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="规格：" prop="spec">
        <el-input v-model="value.spec"></el-input>
      </el-form-item>
      <el-form-item label="商品上架：">
        <el-switch
          v-model="value.publishStatus"
          :active-value="1"
          :inactive-value="0">
        </el-switch>
      </el-form-item>
      <el-form-item label="生产日期：">
        <el-input v-model="value.dateOfManufacture"></el-input>
        <!-- <el-date-picker
          v-model="value.dateOfManufacture"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期">
        </el-date-picker> -->
      </el-form-item>
      <el-form-item label="保质期：">
        <el-input v-model="value.qualityGuaranteePeriod"></el-input>
      </el-form-item>
      <el-form-item label="商品介绍：" >
          <tinymce :width="580" :height="200" class="hideupload" v-model="value.description"></tinymce>
        <!-- <el-input
          :autoSize="true"
          v-model="value.description"
          type="textarea"
          :rows="5"
          placeholder="请输入内容"></el-input> -->
      </el-form-item>
      <el-form-item label="商品货号：">
        <el-input v-model="value.productSn"></el-input>
      </el-form-item>
      <el-form-item label="商品售价：">
        <el-input v-model="value.price"></el-input>
      </el-form-item>
      <el-form-item label="市场价：">
        <el-input v-model="value.originalPrice"></el-input>
      </el-form-item>
      <!-- <el-form-item label="商品库存：">
        <el-input v-model="value.stock"></el-input>
      </el-form-item> -->
      <el-form-item label="计量单位：">
        <el-input v-model="value.unit"></el-input>
      </el-form-item>
      <!-- <el-form-item label="商品重量：">
        <el-input v-model="value.weight" style="width: 300px"></el-input>
        <span style="margin-left: 20px">克</span>
      </el-form-item> -->
      <el-form-item label="排序">
        <el-input v-model="value.sort"></el-input>
      </el-form-item>
      <el-form-item label="商品图片：" prop="selectProductPics">
        <multi-upload v-model="selectProductPics"></multi-upload>
      </el-form-item>
      <el-form-item style="text-align: center">
        <!-- <el-button type="primary" size="medium" @click="handleNext('productInfoForm')">下一步，填写商品促销</el-button> -->
        <el-button type="primary" size="medium" @click="handleFinishCommit">完成，提交商品</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {fetchListWithChildren} from '@/api/productCate'
  import {fetchList as fetchBrandList,fetchOriginList} from '@/api/brand'
  import {getProduct, selectCompList} from '@/api/product';
  import SingleUpload from '@/components/Upload/singleUpload'
  import MultiUpload from '@/components/Upload/multiUpload'
  import Tinymce from '@/components/Tinymce'

  export default {
    name: "ProductInfoDetail",
    components: {SingleUpload, MultiUpload, Tinymce},
    props: {
      value: Object,
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        hasEditCreated:false,
        //选中商品分类的值
        selectProductCateValue: [],
        productCateOptions: [],
        brandOptions: [],
        originOptions:[],
        supplierOptList: [],
        cascaderPlaceholder:'',
        rules: {
          name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
          subTitle: [{required: true, message: '请输入商品副标题', trigger: 'blur'}],
          productCategoryId: [{required: true, message: '请选择商品分类', trigger: 'blur'}],
          brandId: [{required: true, message: '请选择商品品牌', trigger: 'blur'}],
          compId: [{required: true, message: '请选择供应商', trigger: 'blur'}],
          placeOfProductionId: [{required: true, message: '请选择生产地', trigger: 'blur'}],
          description: [{required: true, message: '请输入商品介绍', trigger: 'blur'}],
          requiredProp: [{required: true, message: '该项为必填项', trigger: 'blur'}],
          spec: [{required: true, message: '该项为必填项', trigger: 'blur'}],
          description: [{required: true, message: '该项为必填项', trigger: 'blur'}],
          price: [{required: true, message: '该项为必填项', trigger: 'blur'}],
          qualityGuaranteePeriod: [{required: true, message: '该项为必填项', trigger: 'blur'}],
          selectProductPics: [ {required: true, message: '请上传商品图片', trigger: 'blur'}],
        }
      };
    },
    created() {
      this.getProductCateList();
      this.getBrandList();
      this.getSupplierOptList();
    },
    computed:{
      //商品的编号
      productId(){
        return this.value.id;
      },
      //商品的主图和画册图片
      selectProductPics:{
        get:function () {
          let pics=[];
          if(this.value.pic===undefined||this.value.pic==null||this.value.pic===''){
            return pics;
          }
          pics.push(this.value.pic);
          if(this.value.albumPics===undefined||this.value.albumPics==null||this.value.albumPics===''){
            return pics;
          }
          let albumPics = this.value.albumPics.split(',');
          for(let i=0;i<albumPics.length;i++){
            pics.push(albumPics[i]);
          }
          return pics;
        },
        set:function (newValue) {
          if (newValue == null || newValue.length === 0) {
            this.value.pic = null;
            this.value.albumPics = null;
          } else {
            this.value.pic = newValue[0];
            this.value.albumPics = '';
            if (newValue.length > 1) {
              for (let i = 1; i < newValue.length; i++) {
                this.value.albumPics += newValue[i];
                if (i !== newValue.length - 1) {
                  this.value.albumPics += ',';
                }
              }
            }
          }
        }
      }
    },
    watch: {
      productId:function(newValue){
        if(!this.isEdit)return;
        if(this.hasEditCreated)return;
        if(newValue===undefined||newValue==null||newValue===0)return;
        this.handleEditCreated();
      },
      selectProductCateValue: function (newValue) {
        // console.log('newValue',newValue);
        if (newValue != null && newValue.length === 2) {
          // 大类ID
          this.value.productBigCategoryId = newValue[0];
          // 大类名称
          this.value.productBigCategoryName= this.getBigCateNameById(this.value.productBigCategoryId);

          this.value.productCategoryId = newValue[1];
          this.value.productCategoryName= this.getCateNameById(this.value.productCategoryId);
          this.cascaderPlaceholder = this.value.productBigCategoryName + " / " + this.value.productCategoryName ;
        } else {
          this.value.productCategoryId = null;
          this.value.productCategoryName=null;
          this.value.productBigCategoryId = null;
          this.value.productBigCategoryName = null;
        }
      },
      'value.compId'(newValue) {
        this.getOriginList(newValue);
      }
    },
    methods: {
      //处理编辑逻辑
      handleEditCreated(){
        if(this.value.productCategoryId!=null){
          this.selectProductCateValue.push(this.value.cateParentId);
          this.selectProductCateValue.push(this.value.productCategoryId);
        }
        this.hasEditCreated=true;
      },
      getProductCateList() {
        fetchListWithChildren().then(response => {
          // console.log('getProductCateList',JSON.parse(JSON.stringify(response)))
          let list = response.data;
          this.productCateOptions = [];
          for (let i = 0; i < list.length; i++) {
            let children = [];
            if (list[i].children != null && list[i].children.length > 0) {
              for (let j = 0; j < list[i].children.length; j++) {
                children.push({label: list[i].children[j].name, value: list[i].children[j].id});
              }
            }
            this.productCateOptions.push({label: list[i].name, value: list[i].id, children: children});
          }
        });

      },
      getBrandList() {
        fetchBrandList({pageNum: 1, pageSize: 100}).then(response => {
          this.brandOptions = [];
          let brandList = response.data.list;
          for (let i = 0; i < brandList.length; i++) {
            this.brandOptions.push({label: brandList[i].name, value: brandList[i].id});
          }
        });
      },
      /** 获取供应商下拉列表 */
      getSupplierOptList() {
        selectCompList().then(response => {
          this.supplierOptList = response.data;
        });
      },
      getOriginList(compId) {
        if(!compId) { return; }
        fetchOriginList(compId).then(response => {
          this.originOptions = [];
          let originList = response.data;
          for (let i = 0; i < originList.length; i++) {
            this.originOptions.push({label: originList[i].text, value: originList[i].lable});
          }
        });
      },
      getCateNameById(id){
        let name=null;
        for(let i=0;i<this.productCateOptions.length;i++){
          for(let j=0;j<this.productCateOptions[i].children.length;j++){
            if(this.productCateOptions[i].children[j].value===id){
              name=this.productCateOptions[i].children[j].label;
              return name;
            }
          }
        }
        return name;
      },
      getBigCateNameById(id){
        let bigName=null;
        for(let i=0;i<this.productCateOptions.length;i++){
            if(this.productCateOptions[i].value===id){
              bigName=this.productCateOptions[i].label;
              return bigName;
            }
        }
        return bigName;
      },
      handleNext(formName){
        this.$refs[formName].validate((valid) => {
           console.log('this.$refs[formName]',this.$refs[formName]);
          if (valid) {
            this.$emit('nextStep');
          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      },
      handleBrandChange(val) {
        let brandName = '';
        for (let i = 0; i < this.brandOptions.length; i++) {
          if (this.brandOptions[i].value === val) {
            brandName = this.brandOptions[i].label;
            break;
          }
        }
        this.value.brandName = brandName;
      },
      handleSupplierChange(val) {
        this.value.placeOfProductionId = '';
        this.getOriginList(val);
        let supplierInfoObj = {};
        supplierInfoObj = this.supplierOptList.find(item => {
          return item.value === val;
        });
        this.value.compName = supplierInfoObj.label;
      },
      handleOriginChange(val) {
        let placeOfProduction = '';
        for (let i = 0; i < this.originOptions.length; i++) {
          if (this.originOptions[i].value === val) {
            placeOfProduction = this.originOptions[i].label;
            break;
          }
        }
        this.value.placeOfProduction = placeOfProduction;
      },
      handleFinishCommit(){
        console.log('1111');
        if(!this.selectProductPics || (this.selectProductPics || []).length==0){
          this.$message({
            message: '请上传商品相册',
            type: 'error',
            duration:1000
          });
          return;
        }
        this.$emit('finishCommit',this.isEdit);
      }
    }
  }
</script>

<style>
.el-cascader input::-webkit-input-placeholder {color:#717171!important;}
.hideupload  /deep/ .editor-custom-btn-container{display: none;}
</style>
