<style scope>
  .gd_Item {
    cursor: pointer;
    border: 1px solid #dcdfe6;
    margin: 0 0 5px 5px;
    padding: 0px 8px;
    border-radius: 5px;
    font-size: 12px;
    line-height: 24px;
    display: inline-block;
  }

  .order_Dialog .checkSpec {
    border: 1px solid red !important;
  }

  .order_Dialog .el-input__inner {
    height: 32px !important;
  }

  .goodAddress {
    font-size: 13px;
    color: #409EFF;
    cursor: pointer;
  }

  .gdDis_Item {
    background-color: #e1e3e6 !important;
  }

</style>
<template>
  <div class="flexOne goodlist">
    <div class="query-box">
      <ul>
        <li>
          <span>
            <em>商品分类</em>
            <el-select v-model="showCategoryName" :placeholder="$t('pub.pleaseSel')" multiple clearable collapse-tags
              @change="selectChange">
              <el-option :value="chooseCategroyArray" style="height: auto">
                <el-tree :data="CategoryList" show-checkbox node-key="Id" ref="tree" highlight-current
                  :props="defaultProps" @check-change="categoryCheckChange"></el-tree>
              </el-option>
            </el-select>
          </span>
        </li>
        <li>
          <span>
            <em>商品名称</em>
            <el-input v-model="msg.Name" class="w150" @keyup.enter.native="getGoodList" clearable></el-input>
          </span>
        </li>
        <li>
          <input type="button" class="hollowFixedBtn" :value="$t('pub.searchBtn')" @click="resetPageIndex" /> &nbsp;
        </li>
      </ul>
    </div>
    <el-pagination background @current-change="handleCurrentChange" :current-page.sync="msg.currentPage"
      layout="total,prev, pager, next, jumper" :page-size="msg.pageSize" :total="msg.total">
    </el-pagination>
    <table class="singeRowTable" border="0" cellspacing="0" cellpadding="0" v-loading="loading">
      <thead>
        <tr>
          <th style="width:100px;">{{$t('hotel.hotel_SerialNumber')}}</th>
          <th style="width:200px;">分类</th>
          <th>
            商品名称
          </th>
          <th style="width:200px;">
            库存
          </th>
          <th style="width:200px;">
            售价
          </th>
          <th style="width:200px;">
            分享赚
          </th>
          <th style="width:200px;">
            购买省
          </th>
          <th style="width:150px;">
            操作
          </th>
        </tr>
      </thead>
      <tbody v-for="(item,index) in DataList" :key="index">
        <tr>
          <td>
            {{item.id}}
          </td>
          <td>
            <template
              v-if="item.erpgoodobj&&item.erpgoodobj.goods&&item.erpgoodobj.goods.cats&&item.erpgoodobj.goods.cats.length>0">
              <div v-for="(subItem,subIndex) in item.erpgoodobj.goods.cats" :key="subIndex" style="margin:2px 0;">
                <el-tag size="small">{{subItem.CategoryName}}</el-tag>
              </div>
            </template>
          </td>
          <td style="text-align:left;padding:0 10px;">
            {{item.name}}
          </td>
          <td>
            {{item.goods_stock}}
          </td>
          <td>
            {{item.price}} 起
          </td>
          <td>
            <template v-if="item.erpgoodobj&&item.erpgoodobj.goods">
              {{item.erpgoodobj.goods.share}} 元
            </template>
          </td>
          <td>
            <template v-if="item.erpgoodobj&&item.erpgoodobj.goods">
              {{item.erpgoodobj.goods.myBuyCommission}} 元
            </template>
          </td>
          <td>
            <el-button type="primary" size="small" icon="iconfont icon-beizhu"
              style="background:#AD9AF6; border-color:#AD9AF6; border-radius: 0;padding:4px;"
              @click="clreaMsg(),currentGoodsObj={},currentGoodsObj=item,calcTotalPrice(),orderDialog=true;"> 下单
            </el-button>
          </td>
        </tr>
      </tbody>
    </table>
    <el-pagination background @current-change="handleCurrentChange" :current-page.sync="msg.currentPage"
      layout="total,prev, pager, next, jumper" :page-size="msg.pageSize" :total="msg.total">
    </el-pagination>
    <el-dialog title="下单" :visible.sync="orderDialog" custom-class="order_Dialog" width="400px">
      <div style="margin-bottom:20px;font-size:16px;">
        {{currentGoodsObj.name}}
      </div>
      <el-form label-width="80px" size="small">
        <template>
          <template v-if="currentGoodsObj.goods_stock>0">
            <template v-for="(subItem,subIndex) in currentGoodsObj.attr_groups">
              <el-form-item :key="subIndex" :label="subItem.attr_group_name" style="line-height:25px;">
                <span class="gd_Item" v-for="(childItem,childIndex) in subItem.attr_list" :key="childIndex"
                  @click="chooseSpec(subIndex,childIndex),calcTotalPrice()"
                  :class="{'checkSpec':subItem.checkId==childItem.attr_id}">
                  {{childItem.attr_name}}
                </span>
              </el-form-item>
            </template>
          </template>
          <template v-else>
            <template v-for="(subItem,subIndex) in currentGoodsObj.attr_groups">
              <el-form-item :key="subIndex" :label="subItem.attr_group_name" style="line-height:25px;">
                <span class="gd_Item gdDis_Item" v-for="(childItem,childIndex) in subItem.attr_list" :key="childIndex">
                  {{childItem.attr_name}}
                </span>
              </el-form-item>
            </template>
          </template>
        </template>
        <el-form-item :label="$t('objFill.goumaishuliang')" size="small">
          <el-input-number @change="calcTotalPrice()" size="small" style="height:32px;" v-model="orderMsg.Number"
            :min="1" :max="10" label="请输入购买数量"></el-input-number>
        </el-form-item>
        <el-form-item label="选择用户" size="small">
          <el-select size="small" v-model="orderMsg.mallUserId" filterable remote reserve-keyword placeholder="请输入微信昵称"
            :remote-method="getWechatData" @change="weChatChange">
            <el-option v-for="wItem in weChatData" :key="wItem.Id" :label="wItem.Name" :value="wItem.Id">
              <span style="float: left">{{ wItem.Name }}
                <template v-if="wItem.ShopId>0">
                  <span style="color:red;">【{{ wItem.ShopName }}】</span>
                </template>
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收货地址" size="small">
          <el-select size="small" v-model="orderMsg.AddressId" :placeholder="$t('pub.pleaseSel')" @change="ChangeAddress">
            <el-option v-for="aItem in addressList" :key="aItem.Id" :label="aItem.Name" :value="aItem.Id">
              <span style="float: left">{{ aItem.Name }}【{{aItem.DistrictAddress}}{{aItem.Address}}】</span>
            </el-option>
          </el-select>
          <span class="goodAddress" @click="addAddress()">新增</span>
        </el-form-item>
        <el-form-item label="合计" size="small">
          商品:¥<span style="color:red">{{orderMsg.GoodPrice}}</span>元+ 
          运费:¥<span style="color:red">{{orderMsg.FreightMoney}}</span>元
          = <span style="color:red">¥{{orderMsg.TotalPrice}}</span>元
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="orderDialog = false">{{$t('pub.cancelBtn')}}</el-button>
        <el-button size="small" type="danger" @click="SaveOrder()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="新增地址" :visible.sync="goodVisible" width="600px">
      <el-form ref="AddressMsg" :model="AddressMsg" :rules="rules" label-width="100px">
        <el-form-item label="收货人" prop="Name">
          <el-input class="w300" v-model="AddressMsg.Name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('scen.sc_tel')" prop="Mobile">
          <el-input class="w300" v-model="AddressMsg.Mobile"></el-input>
        </el-form-item>
        <el-form-item label="省市区" prop="position">
          <el-cascader class="w300" v-model="AddressMsg.position" :placeholder="addressName" :options="provinceList"
            @active-item-change="handleItemChange" :props="props"></el-cascader>
        </el-form-item>
        <el-form-item :label="$t('hotel.hotel_detailinfo')" prop="Address">
          <el-input v-model="AddressMsg.Address" :placeholder="$t('hotel.hotel_detailInfo')" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="goodVisible = false">{{$t('pub.cancelBtn')}}</el-button>
        <el-button size="small" type="danger" @click="saveInfo('AddressMsg')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="二维码收款" :visible.sync="payVisible" width="400px">
      <payMall :item="payObj" @closeDia="closeDia" @getGoodList="getGoodList" ref="payChild"></payMall>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelPay()">{{$t('pub.cancelBtn')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import payMall from "../commonPage/payMall.vue";
  export default {
    data() {
      return {
        payObj: {
          orderId: 0,
          OrderSource: 16,
          
          TotalPrice: 0,
          contactName: "",
          customerId: 0,
          outBranchId: 0,
          User_Id: 0
        },
        statusValue: 0, //请选择
        //数据列表
        DataList: [],
        CategoryList: [], //分类列表
        loading: false,
        showCategoryName: "",
        chooseCategroyArray: [],
        //默认属性
        defaultProps: {
          children: 'ChildList',
          label: 'Name'
        },
        //查询参数
        msg: {
          currentPage: 1,
          //总条数
          total: 0,
          pageIndex: 1,
          pageSize: 10,
          Name: "", //商品名称
          CategoryIds: "", //商品分类
          IsGetShare: 1, //获取分销
          ERPUserId: 0, //商城用户Id
          ERPSmallShopId: 0, //用户店铺Id
        },
        weChatData: [], //微信用户列表
        addressList: [], //收货地址列表
        orderMsg: {
          GoodsId: 0, //商品编号
          Number: 1, //商品数量
          SpecificationSort: "", //规格
          mallUserId: "", //用户Id
          AddressId: '', //收货地址Id
          GoodPrice:0,//商品价格
          TotalPrice: 0, //总价格
          specificationNameList: [], //规格列表
          FreightMoney: 0, //运费
        },
        //当前选中商品
        currentGoodsObj: {},
        chooseAddressObj: {}, //选中的地址
        //新增地址msg
        AddressMsg: {
          Id: 0,
          Name: '',
          Mobile: '',
          Province: '',
          City: '',
          District: '',
          Address: '',
          NewUserId: 0,
          position: [],
        },
        addressName: '请选择',
        provinceList: [], //省市县列表
        props: {
          value: 'value',
          children: 'cities'
        },
        rules: {
          Name: [{
            required: true,
            message: "请输入收件人姓名",
            trigger: "blur"
          }],
          Mobile: [{
            required: true,
            message: "请输入联系方式",
            trigger: "blur"
          }],
          Address: [{
            required: true,
            message: "请输入详细地址",
            trigger: "blur"
          }],
          position: [{
            type: 'array',
            required: true,
            message: '请选择省市区',
            trigger: 'change'
          }],
        },
        orderDialog: false,
        goodVisible: false,
        payVisible: false,
      };
    },
    components: {
      payMall: payMall,
    },
    methods: {
      //清空数据
      clreaMsg() {
        this.orderMsg.GoodsId = 0;
        this.orderMsg.Number = 1;
        this.orderMsg.SpecificationSort = "";
        this.orderMsg.mallUserId = "";
        this.orderMsg.AddressId = '';
        this.orderMsg.GoodPrice=0;
        this.orderMsg.TotalPrice = 0;
        this.orderMsg.specificationNameList = [];
        this.orderMsg.FreightMoney = 0;
        //清空临时对象
        this.currentGoodsObj = {};
        this.chooseAddressObj = {};
        this.weChatData = [];
        this.addressList = [];
      },
      //选择规格
      chooseSpec(index, subIndex) {
        var tempObj = this.currentGoodsObj.attr_groups[index].attr_list[subIndex];
        if (this.currentGoodsObj.attr_groups[index].checkId != tempObj.attr_id) {
          this.currentGoodsObj.attr_groups[index].checkId = tempObj.attr_id;
          this.currentGoodsObj.attr_groups[index].checkName = tempObj.attr_name;
        } else {
          this.currentGoodsObj.attr_groups[index].checkId = 0;
          this.currentGoodsObj.attr_groups[index].checkName = this.currentGoodsObj.attr_groups[index]
            .attr_group_name;
        }
      },
      //计算总价格
      calcTotalPrice() {
        let sign = '';
        let specificationNameList = [];
        var tempSku = {};
        if (this.currentGoodsObj.attr_groups && this.currentGoodsObj.attr_groups.length > 0) {
          this.currentGoodsObj.attr_groups.forEach(specItem => {
            if (specItem.checkId != -1) {
              sign += (sign == '' ? '' : ':') + specItem.checkId;
              var subName = specItem.attr_group_name + ":" + specItem.checkName;
              specificationNameList.push(subName);
            }
          });
        }
        if (this.currentGoodsObj.attr && this.currentGoodsObj.attr.length) {
          this.currentGoodsObj.attr.forEach(specValue => {
            if (specValue.sign_id == sign) {
              tempSku = specValue;
            }
          });
        }
        if (tempSku != null && tempSku.price) {
          this.orderMsg.FreightMoney = this.currentGoodsObj.erpgoodobj.goods.express;
          this.orderMsg.GoodsId = this.currentGoodsObj.id;
          this.orderMsg.SpecificationSort = tempSku.sign_id;
          this.orderMsg.specificationNameList = specificationNameList;
          this.orderMsg.GoodPrice=(parseFloat(tempSku.price) * parseFloat(this.orderMsg.Number)).toFixed(2);
          this.orderMsg.TotalPrice = (parseFloat(tempSku.price) * parseFloat(this.orderMsg.Number) + parseFloat(this
            .orderMsg.FreightMoney)).toFixed(2);
        }
      },
      //商品分类下拉框改变
      selectChange(e) {
        var arrNew = [];
        var dataLength = this.chooseCategroyArray.length;
        var eleng = e.length;
        for (let i = 0; i < dataLength; i++) {
          for (let j = 0; j < eleng; j++) {
            if (e[j] === this.chooseCategroyArray[i].Name) {
              arrNew.push(this.chooseCategroyArray[i])
            }
          }
        }
        this.$refs.tree.setCheckedNodes(arrNew); //设置勾选的值
      },
      //商品分类选中
      categoryCheckChange() {
        //这里两个true,1. 是否只是叶子节点 2. 是否包含半选节点(就是使得选择的时候不包含父节点)
        let res = this.$refs.tree.getCheckedNodes(true, true);
        let arrLabel = [];
        let arr = [];
        res.forEach(item => {
          arrLabel.push(item.Name);
          arr.push(item);
        });
        this.chooseCategroyArray = arr;
        this.showCategoryName = arrLabel;
      },
      //获取商品分类列表
      getCategroy() {
        let msg1 = {
          Id: 0,
          Name: '',
          Tier: 0,
          ParentId: 0,
          Enabled: 1,
          IsShow: 1,
        }
        this.mallapipost("/api/AppletGoods/GetProductCategoryTreeList", msg1, res => {
          if (res.data.resultCode == 1) {
            let pageData = res.data.data;
            this.CategoryList = pageData;
          }
        })
      },
      //获取商品列表
      getGoodList() {
        this.msg.CategoryIds = "";
        var tempCategory = "";
        if (this.chooseCategroyArray && this.chooseCategroyArray.length > 0) {
          this.chooseCategroyArray.forEach(item => {
            tempCategory += item.Id + ",";
          })
        }
        this.msg.CategoryIds = tempCategory.substring(0, tempCategory.lastIndexOf(','));
        if (this.getLocalStorage().MallUserId) {
          this.msg.ERPUserId = this.getLocalStorage().MallUserId;
        }
        if (this.getLocalStorage().MallSmallShopsId) {
          this.msg.ERPSmallShopId = this.getLocalStorage().MallSmallShopsId;
        }
        this.loading = true;
        this.DataList = [];
        this.mallapipost(
          "/api/AppletGoods/GetAppletGoodsPageListForZY",
          this.msg,
          res => {
            this.loading = false;
            if (res.data.resultCode == 1) {
              var tempArray = res.data.data.pageData;
              if (tempArray && tempArray.length > 0) {
                tempArray.forEach(item => {
                  if (item.attr_groups && item.attr_groups.length > 0) {
                    item.attr_groups.forEach(specItem => {
                      specItem.checkId = 0; //选择的规格索引
                      specItem.checkName = ""; //选择的规格名称
                    })
                  }
                })
              }
              this.DataList = tempArray;
              this.msg.total = res.data.data.count;
            }
          });
      },
      //分页
      handleCurrentChange(val) {
        this.msg.pageIndex = val;
        this.getGoodList();
      },
      //重新查询
      resetPageIndex() {
        this.msg.pageIndex = 1;
        this.msg.currentPage = 1;
        this.getGoodList();
      },
      //获取微信用户列表
      getWechatData(keyWords) {
        this.weChatData = [];
        this.addressList = [];
        var qMsg = {
          Name: keyWords
        };
        if (keyWords && keyWords != '') {
          this.mallapipost(
            "/api/User/GetMemberUserListExt",
            qMsg,
            res => {
              if (res.data.resultCode == 1) {
                this.weChatData = res.data.data;
              }
            });
        }
      },
      //获取用户收货地址
      weChatChange() {
        this.addressList = [];
        this.mallapipost(
          "/api/User/GetShippingAddressList", {
            NewUserId: this.orderMsg.mallUserId
          },
          res => {
            if (res.data.resultCode == 1) {
              this.addressList = res.data.data;
            }
          });
      },
      //切换收货地址
      ChangeAddress() {
        let addressObj = this.addressList.find(item => {
          return item.Id === this.orderMsg.AddressId; //筛选出匹配数据
        });
        this.chooseAddressObj = addressObj;
      },
      //下单
      SaveOrder() {
        var DetailList = [{
          SpecificationSort: this.orderMsg.SpecificationSort,
          Number: this.orderMsg.Number,
          GoodsId: this.orderMsg.GoodsId,
          SpecificationList: this.orderMsg.specificationNameList
        }];
        let orderData = {
          Consignee: this.chooseAddressObj.Name,
          Mobile: this.chooseAddressObj.Mobile,
          Province: this.chooseAddressObj.Province,
          City: this.chooseAddressObj.City,
          District: this.chooseAddressObj.District,
          ShoppingAddress: this.chooseAddressObj.Address,
          BuyerMessage: "", //买家留言
          DeliveryMethod: 1, //1-快递配送,2-到店自提,3-同城配送
          DetailList: DetailList,
          User_Coupon_Id: 0,
          CouponMoney: 0, //优惠金额
          FreightMoney: this.orderMsg.FreightMoney, //运费
          Income: this.orderMsg.TotalPrice,
          IsFormShoppingCart: 2,
          Use_Integral: 0,
          ShoppingCartIdList: [], //购物车编号
          AnchorName: "", //主播名称
          NewUserId: this.orderMsg.mallUserId,
          NewShopId: this.getLocalStorage().MallSmallShopsId,
          OrderSource: 6, //ERP下单
        }
        if (orderData.DetailList == null || (orderData.DetailList && orderData.DetailList.length == 0) ||
          (orderData.DetailList && orderData.DetailList.length > 0 && orderData.DetailList[0].SpecificationList &&
            orderData.DetailList[0].SpecificationList
            .length == 0)) {
          this.Error('请选择规格!');
          return;
        }

        if (orderData.NewUserId == "" || Number(orderData.NewUserId) <= 0) {
          this.Error('请选择用户!');
          return;
        }
        if (orderData.Consignee == "") {
          this.Error('请选择收货地址!');
          return;
        }
        this.mallapipost("/api/AppletOrder/SetERPGoodsOrderInfo", orderData, res => {
          if (res.data.resultCode == 1) {
            let userInfo = this.getLocalStorage();
            var resData = res.data.data;
            this.payObj.orderId = resData.OrderId;
            this.payObj.TotalPrice = this.orderMsg.TotalPrice;
            this.payObj.contactName = userInfo.emName;
            this.payObj.customerId = userInfo.EmployeeId;
            this.payObj.outBranchId = userInfo.RB_Branch_id;
            this.payObj.User_Id = this.orderMsg.mallUserId;
            this.payVisible = true;
            if (this.$refs.payChild) {
              this.$refs.payChild.initData();
            }
            this.Success("下单成功!");
            this.clreaMsg();
            this.orderDialog = false;
          } else {
            this.Error(res.data.message);
          }
        })
      },
      handleItemChange(val) {
        this.getPosition(val)
      },
      getPosition(val, cb) {
        let vm = this; //查询省市县
        let params = {};
        if (!val) { //初始化加载 获取所有省份数据
          params = {
            Id: 1
          }
        } else if (val.length === 1) { //加载二级  获取市级数据
          params = {
            Id: val[0]
          }
        } else { //加载3级   获取县级数据
          params = {
            Id: val[1]
          }
        }
        this.mallapipost("/api/Destination/GetChildList", params, res => {
          if (res.data.resultCode == 1) {
            if (!val) { //初始化加载   查询省份数据
              vm.provinceList = res.data.data.map((e) => {
                return {
                  value: e.ID,
                  label: e.Name,
                  cities: []
                }
              });
            } else if (val.length === 1) { //加载二级    查询该省下市级数据
              vm.provinceList.map((item) => {
                if (item.value === val[0]) {
                  item.cities = res.data.data.map((e) => {
                    return {
                      value: e.ID,
                      label: e.Name,
                      cities: []
                    }
                  })
                }
              })
            } else { //加载3级   查询该省市下县级数据
              vm.provinceList.map((item) => {
                if (item.value === val[0]) {
                  item.cities.map((value) => {
                    if (value.value === val[1]) {
                      value.cities = res.data.data.map((e) => {
                        return {
                          value: e.ID,
                          label: e.Name
                        }
                      })
                    }
                  })
                }
              })
            }
            cb && cb(res);
          }
        })
      },
      //点击新增
      addAddress() {
        if (this.orderMsg.mallUserId == '') {
          this.Error('请选择用户');
        } else {
          this.goodVisible = true;
        }
      },
      //新增
      saveInfo(formName) {
        this.AddressMsg.Province = this.AddressMsg.position[0];
        this.AddressMsg.City = this.AddressMsg.position[1];
        this.AddressMsg.District = this.AddressMsg.position[2];
        this.AddressMsg.NewUserId = this.orderMsg.mallUserId
        this.$refs[formName].validate((valid) => {
          if (valid) {
            delete this.AddressMsg.position //删除position 不传到后台
            this.mallapipost("/api/AppletUser/ERPSetUserShippingAddress", this.AddressMsg, res => {
              if (res.data.resultCode == 1) {
                this.Success(res.data.message);
                this.goodVisible = false;
                this.weChatChange();
              } else {
                this.Error(res.data.message);
              }
            })
          } else {
            return false;
          }
        });
      },
      //调用取消
      cancelPay() {
        this.payVisible = false;
        this.$refs.payChild.clearCount();
      },
      //关闭
      closeDia() {
        this.payVisible = false;
      }
    },
    mounted() {
      this.getCategroy();
      this.getGoodList();
      this.getPosition(null)
    }
  };

</script>