<template>
  <div class="app-container">
    <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">经销商管理</h1>
      <br />
      <!-- 搜索工作栏 -->
      <SearchInfo
        ref="searchForm"
        :searchFormParam="{ queryParams, dataSource }"
        :showSearch.sync="showSearch"
        @handleQuery="handleQuery"
        @resetQuery="resetQuery"
      ></SearchInfo>
    </div>

    <div class="app-container-list main-bgcolor main-radius shopping">
      <div class="shopping-top">
        <div class="shopping-title">经销商列表</div>
        <el-button class="shopping-add-btn" type="primary" plain @click="handleAdd"
          v-hasPermi="['basic:dealer-info:create']">添加经销商</el-button>
      </div>

      <!-- 列表 -->
      <el-table v-loading="loading" :data="list" >
        <el-table-column label="编号" align="center" type="index" width="80" >
          <template v-slot="{ $index }">
            <span>{{($index+1)+ (queryParams.pageNo-1)*queryParams.pageSize }}</span>
          </template>
        </el-table-column>
        <el-table-column label="经销商编码" align="center" prop="dealerId" width="220" >
          <template slot-scope="{ row }">
            <div class="flex-allcenter">
              <span class="more-width-20">{{row.dealerId}}</span>
              <el-button type="text" icon="el-icon-copy-document" @click.stop="copyContent(row.dealerId)"></el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="经销商名称" align="center" prop="dealerName" />
        <el-table-column label="所属商户" align="center" prop="belongBusinessName"/>
        <!-- 负责人就是联系人 -->
        <el-table-column label="负责人" align="center" prop="contactName" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" width="140" />
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template v-slot="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remarks" :show-overflow-tooltip="true"/>
        <el-table-column
          label="操作" fixed="right"
          align="center"
          class-name="small-padding fixed-width"
		  width="150"
        >
          <template v-slot="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['basic:dealer-info:update']"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['basic:dealer-info:delete']"
              >删除</el-button
            >
          </template>
        </el-table-column>
        <div slot="empty">
          <EmptyTable />
        </div>
      </el-table>
      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      v-dialogDrag
      append-to-body
      width="60%"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" label-position="top">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="经销商名称" prop="dealerName">
              <el-input
                v-model="form.dealerName"
                placeholder="请输入经销商名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.dealerId && form.dealerId != ' ' " >
            <el-form-item label="经销商编码" prop="dealerId" >
              <el-input
                v-model="form.dealerId"
                placeholder=""
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属商户" prop="belongBusinessName">
              <div style="display: flex;">
                <el-select v-model="form.belongBusinessId" :placeholder=this.belongBusinessPlaceholder clearable filterable style="flex: 1;"  @change="businessIdChangeToSelectGooods">
                  <el-option v-for="businessInfo in businessNameList"
                  :key="businessInfo.index" :label="businessInfo.businessName" :value="businessInfo.id" @click.native="labelClick(businessInfo.businessName)"/>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input
                v-model="form.contactPhone"
                placeholder="请输入联系方式"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经销区域" prop="commonSaleArea">
              <!-- <div style="display: flex;">
                <CascaderArea  style="flex: 1;" :pca="areaList" :isValue="''+form.commonSaleAreaId" ref="cascaderArea" v-model="form.commonSaleAreaId" @transfer="getArea" @transferId="getAreaId"></CascaderArea>
              </div> -->
              <el-input v-model="form.commonSaleArea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一信用代码" prop="businessCode">
              <el-input v-model="form.businessCode" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remarks" height="100px">
              <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div style="margin-bottom: 22px; display: flex; justify-content: flex-end;">
        <el-button type="primary" @click="openSelectInputDialog">新增销售区域/商品</el-button>
      </div>
      <template v-if="inputInfoListVisible">
        <el-table :data="inputInfoList" >
          <!-- <el-table-column label="省级" align="center" prop="province" />
          <el-table-column label="市级" align="center" prop="city" />
          <el-table-column label="县级" align="center" prop="county" /> -->
          <el-table-column label="商品经销商区域" align="center" prop="saleArea" />
          <el-table-column label="绑定商品" align="center" prop="inputsGoodsName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleEditInputInfo(scope.row)"
                v-hasPermi="['basic:dealer-info:update']"
                v-if="scope.row.newGoods != 1"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleEditNewInputInfo(scope.row)"
                v-hasPermi="['basic:dealer-info:update']"
                v-if="scope.row.newGoods == 1"
                >新增编辑</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteInputInfo(scope.row)"
                v-hasPermi="['basic:dealer-info:delete']"
                v-if="scope.row.newGoods != 1"
                >删除</el-button
              >

              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteNewInputInfo(scope.row)"
                v-hasPermi="['basic:dealer-info:delete']"
                v-if="scope.row.newGoods == 1"
                >新增删除</el-button
              >

            </template>
          </el-table-column>
          <div slot="empty">
            <EmptyTable />
          </div>
        </el-table>
      </template>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="addDealerInfoCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对话框 选择商品 -->
    <!-- 正常情况，可直接销毁弹窗，这样可以不去维护状态 -->
    <el-dialog title="新增区域商品"
      :visible.sync="selectInputVisible" width="900px" v-dialogDrag append-to-body close-on-click-modal
      :before-close="selectInputCancel"
    >
      <el-form ref="formSaleArea" :model="inputCheckedAreaList" :rules="rules" label-position="top">
        <el-form-item label="商品经销区域" prop="commonSaleArea" style="width: 47.5%;">
          <!-- <div style="display: flex;">
            <CascaderArea  style="flex: 0.43;margin-bottom: 20px;" ref="cascaderArea"
            :pca="areaList" :isValue="''+inputCheckedAreaList.commonSaleAreaId"  v-model="inputCheckedAreaList.commonSaleAreaId"
              @transfersAreaCode="getGoodsArea" @transferId="getGoodsAreaId"></CascaderArea>
          </div> -->
          <el-input v-model="inputCheckedAreaList.commonSaleArea" placeholder="请输入商品经销区域"></el-input>
        </el-form-item>
      </el-form>
      <Transfer
        ref="inputTransfer"
        :data="inputInfoOptions"
        :vModel="inputCheckedIdList"
        :renderContent="renderTransferLabel"
        :titles="['可选', '已选']"
        @change="handleSelectChange"
        :leftCurrentPage="leftCurrentPage"
        :rightCurrentPage="rightCurrentPage"
        @handlePageChange="handlePageChange"
        :leftDefaultChecked="leftDefaultChecked"
        :rightDefaultChecked="rightDefaultChecked"
        @left-check-change="transferLeftCheckChange"
        @right-check-change="transferRightCheckChange"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectInputCancel">取 消</el-button>
        <el-button type="primary" @click="submitSelectInput" v-if="addNewAreaGoodsEnable">确 定</el-button>
        <el-button type="primary" @click="submitSelectUpdateInput" v-if="!addNewAreaGoodsEnable">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createDealerInfo,
  updateDealerInfo,
  deleteDealerInfo,
  deleteDealerAreaGoods,
  getDealerInfo,
  getDealerInfoPage,
  createDealerAndAreaGoodsInfo,
  updateDealerAndAreaGoodsInfo,
} from '@/api/basic/dealerInfo';
import {
  createDealerGoods,
  updateDealerGoods,
  getDealerGoods,
  getDealerGoodsQuery,
  deleteDealerGoods,
  getDealerGoodsPage
} from '@/api/basic/dealerGoods';
import { getBusinessNameList } from "@/api/basic/businessInfo";
import { getGoodsInfoPage,getGoodsInfoQuery} from "@/api/basic/goodsInfo";
import {getAreaTree} from "@/api/system/area";
import EmptyTable from '@/components/EmptyTable'
import SearchInfo from '@/components/Customer/SearchForm'
import CascaderArea from "@/components/Customer/Cascader/areaById"
import Transfer from '@/components/Customer/Transfer/index.vue';


export default {
  name: 'DealerInfo',
  components: {
    SearchInfo,
    EmptyTable,
    CascaderArea,
    Transfer,
  },
  data() {
    return {
      //所属商户下拉框提示
      belongBusinessPlaceholder:'请选择所属商户',
      //获取的地区信息列表
      areaList:[],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalGoods: 0,
      // 经销商列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //商户名称列表
      businessNameList:{},
      // 查询参数
      queryGoodsPageParams: {
        pageNo: 1,
        pageSize: 10,
        belongBusinessId: null,
      },
      // 查询参数
      queryGoodsListParams: {
        belongBusinessId: 0,
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        dealerName: null,
        dealerId: null,
        belongBusinessId: null,
        belongBusinessName: null,
        businessCode: null,
        contactPhone: null,
        contactName: null,
        commonSaleArea: null,
        commonSaleAreaId: null,
        createTime: [],
        remarks: null,
      },
      // 查询商品列表参数
      queryDealerGoodsParams: {
        pageNo: 1,
        pageSize: 10,
        dealerId: null,
        dealerName: null,
        goodsId: null,
        goodsName: null,
        saleArea: null,
        saleAreaId: null,
        createTime: [],
        belongBusinessId: null,
        belongBusinessName: null,
      },
      //表单对象
      dataSource: [
        {
          key: 'dealerId', //经销商编码
          itemType: 'input',
          label: '经销商编码',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'dealerName', //经销商名称
          itemType: 'input',
          label: '经销商名称',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'belongBusinessName', //所属商户名称
          itemType: 'input',
          label: '所属商户',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'contactName', //负责人就是联系人
          itemType: 'input',
          label: '负责人',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'contactPhone', //联系电话
          itemType: 'input',
          label: '联系电话',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'createTime', //创建时间
          itemType: 'datePicker',
          label: '创建时间',
          onEnterKeyUp: this.handleQuery,
        },
      ],
      // 表单参数
      form: {},
      formGoods:{},
      // 表单校验
      rules: {
        dealerName: [
          { required: true, message: '经销商名称不能为空', trigger: 'blur' },
        ],
        belongBusinessId: [
          { required: true, message: '所属商户不能为空', trigger: 'blur' },
        ],
        belongBusinessName: [
          { required: true, message: '所属商户不能为空', trigger: 'blur' },
        ],
        contactName: [
          { required: true, message: '联系人姓名不能为空', trigger: 'blur' },
        ],
        contactPhone: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' },
          {
            pattern:  /^1[3|4|5|7|8|9][0-9]{9}$/,
            message: '联系电话格式有误！',
            trigger: 'blur',
          }
        ],
        commonSaleArea: [
          { required: true, message: '销售区域不能为空', trigger: 'blur' },
        ],
        saleArea: [
          { required: true, message: '商品销售区域不能为空', trigger: 'blur' },
        ],
      },

      /***********************  经销商商品信息弹窗相关参数  ************************/
      // 是否显示添加商品弹出框
      // addInputVisible: false,
      // 是否显示经销商所属区域商品表格
      inputInfoListVisible:true,
      // 是否显示新增经销商所属区域商品表格
      // aaddInfoTabVisible:true,
      addNewAreaGoodsEnable:true,
      // 用于存放已添加在库中的商品信息列表
      inputInfoListTemp: [],
      // 已选/已入的商品信息列表
      inputInfoList: [],
      // 新增的区域/商品信息列表
      addInfoList: [],
      //存放非新增的经销商商品信息更新
      addInfoUpdateList:[],
      // 新增的区域/商品列表显示信息
      addInfoTabList: [],
      dataAreaGoodsInfo:{dealerInfo:undefined,areaGoodsList:undefined,areaGoodsUpdateList:undefined},
      //选择的商品的ID集合
      inputInfoIdList: [],
      //新增商品的临时index
      updateNewIndex:-1,
      //当前所操作的新增商品的updateNewIndex
      newIndex:undefined,
      //当前更新的经销商商品ID
      updateDealerGoodsId:undefined,
      /***********************  选择商品弹窗相关参数  ************************/
      //更新商品信息操作标志
      updateAreaGoodsDoFlag:0,
      selectInputVisible: false,
      // 已选中的商品列表【临时】，只在弹窗时作为临时存放用
      inputCheckedIdList: [],
      //选择的销售区域
      inputCheckedAreaList: {
        commonSaleArea:'',
        commonSaleAreaId:undefined
      },
      // 商品可选列表
      inputInfoOptions: [],
      // 这里定义俩个参数是为了每次重新打开组件时可以重置当前页码到1
      leftCurrentPage: 1,
      rightCurrentPage: 1,
      leftDefaultChecked: [],
      rightDefaultChecked: [],
    }
  },

  created() {
    this.getList()
    this.getAreaList()
  },

  methods: {
    /** 地区查询列表 */
    getAreaList() {
      getAreaTree().then(response => {
        this.areaList = response.data;
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      if(this.queryParams.dealerId == ''){
        this.queryParams.dealerId = null;
      }
      if(this.queryParams.contactPhone == ''){
        this.queryParams.contactPhone = null;
      }
      // 执行查询
      getDealerInfoPage(this.queryParams).then((response) => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
      });
    },
    /** 获取当前分页列表 */
    getDealerInfoList() {
      this.loading = true
      let queryParams = {
          pageNo: this.queryParams.pageNo,
          pageSize: this.queryParams.pageSize,
      }
      // 执行查询
      getDealerInfoPage(queryParams).then((response) => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
      });
    },
    /** 获取商户名称列表 */
    getBusinessNameList(){
      getBusinessNameList().then(response => {
        this.businessNameList = response.data;
      });
    },
    /** 查询经销商商品列表 */
    getDealerGoodsList(dealerId,belongBusinessId) {
      this.queryGoodsListParams.belongBusinessId = null
      this.queryDealerGoodsParams.dealerId = dealerId
      this.queryDealerGoodsParams.belongBusinessId = belongBusinessId
      // 执行查询
      getGoodsInfoQuery(this.queryGoodsListParams).then(response => {
        const goodsList = response.data
        getDealerGoodsQuery(this.queryDealerGoodsParams).then((response) => {
          const data = response.data
          const addList = []
          for(let i = 0; i < data.length; i++) {
            let goodInfo = goodsList.filter(item => item.goodsId == data[i].goodsId)
            let goodInfoId = goodInfo.length != 0 ? goodInfo[0].id : undefined
            addList.push({
              saleArea:data[i].saleArea,
              // province:data[i].saleArea.split('/')[0],
              // city:data[i].saleArea.split('/')[1],
              // county:data[i].saleArea.split('/')[2],
              inputsGoodsName:data[i].goodsName,
              id:data[i].id,
              areaId:data[i].saleAreaId,
              goodsId:data[i].goodsId,
              gid:(goodInfoId == undefined ? 0 : goodInfoId),
              newGoods:0
            });
          }
          this.inputInfoList = addList
          this.inputInfoListTemp = addList
          if(this.addInfoTabList.length > 0){
            this.inputInfoList = this.addInfoTabList.concat(this.inputInfoListTemp);
          }
          this.totalGoods = response.data.total
          this.queryGoodsListParams.belongBusinessId = 0
          console.log(this.inputInfoList)
          console.log(this.totalGoods)
        });
      });
    },
    /** 取消按钮 */
    /** 关闭新增经销商弹窗 */
    addDealerInfoCancel() {
      this.open = false;
      this.reset();
      this.addInfoList = [];
      this.addInfoUpdateList = []
      this.inputInfoList = [];
      this.inputInfoIdList = [];
      this.addInfoTabList = []
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        dealerName: undefined,
        dealerId: undefined,
        belongBusinessId: undefined,
        belongBusinessName: undefined,
        businessCode: undefined,
        contactPhone: undefined,
        contactName: undefined,
        commonSaleArea: undefined,
        commonSaleAreaId: undefined,
        inputCheckedAreaList: {commonSaleArea:'',commonSaleAreaId:undefined},
        dataAreaGoodsInfo:{dealerInfo:undefined,areaGoodsList:undefined,areaGoodsUpdateList:undefined},
        remarks: undefined,
      }
      this.addInfoTabList = [];
      this.addInfoList = [];
      this.inputInfoList = [];
      this.addInfoUpdateList = [];
      this.totalGoods = 0;
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm", "searchForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getBusinessNameList();
      this.open = true
      this.inputInfoListVisible = true
      this.belongBusinessPlaceholder = '请选择所属商户'
      this.title = '添加经销商'
      this.updateNewIndex = -1;
    },
    /** 经销商编辑按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.addInfoTabList = []
      const id = row.id
      const dealerId = row.dealerId
      const belongBusinessId = row.belongBusinessId
      this.getBusinessNameList();
      this.getDealerGoodsList(dealerId,belongBusinessId)
      this.updateNewIndex = -1;
      getDealerInfo(id).then((response) => {
        this.form = response.data
        this.open = true
        // this.aaddInfoTabVisible = false
        this.inputInfoListVisible = true

        //当商户被删除时，无法显示对应的商户名称，重新定义
        let isTip = true;
        for(var x=0;x<this.businessNameList.length;x++){
          if(this.businessNameList[x].id == this.form.belongBusinessId){
            isTip = false;
          }
        }
        if( isTip ) {
          this.form.belongBusinessId = undefined
          this.form.belongBusinessName = undefined
          this.belongBusinessPlaceholder = '所属商户已删除，请重新选择'
        }else{
          this.belongBusinessPlaceholder = '请选择所属商户'
        }

        this.title = '修改经销商'
        console.log("---------------")
        console.log(this.form)
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return
        }
        // 修改的提交
        if (this.form.id != null) {
          if(this.addInfoList.length === 0 && this.addInfoUpdateList.length === 0){
            updateDealerInfo(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getDealerInfoList()
            })
          }else{
            this.dataAreaGoodsInfo.dealerInfo = this.form
            this.dataAreaGoodsInfo.areaGoodsList = this.addInfoList
            this.dataAreaGoodsInfo.areaGoodsUpdateList = this.addInfoUpdateList
            updateDealerAndAreaGoodsInfo(this.dataAreaGoodsInfo).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getDealerInfoList()
            })
          }
          return
        }
        // 经销商信息添加的提交 经销商区域/商品添加的提交
        if(this.addInfoList.length === 0){
          createDealerInfo(this.form).then((response) => {
            if(response.data){
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getDealerInfoList()
              this.reset()
            }
          })
        }else{
          this.dataAreaGoodsInfo.dealerInfo = this.form
          this.dataAreaGoodsInfo.areaGoodsList = this.addInfoList
          createDealerAndAreaGoodsInfo(this.dataAreaGoodsInfo).then((response) => {
            if(response.data){
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getDealerInfoList()
              this.reset()
            }
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dealerId = row.dealerId
      const id = row.id
      this.$modal
        .confirm('是否确认删除该经销商？')
        .then(function () {
          return deleteDealerAreaGoods(id)
        })
        .then(() => {
          this.getDealerInfoList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },

    /** 删除经销商商品信息 */
    handleDeleteInputInfo(row) {
      const id = row.id
      const dealerId = this.form.dealerId
      const belongBusinessId = this.form.belongBusinessId

      this.$modal.confirm('是否确认删除该区域商品').then(function() {
        return deleteDealerGoods(id);
      }).then(() => {
        this.getDealerGoodsList(dealerId,belongBusinessId);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 删除新增经销商商品信息 */
    handleDeleteNewInputInfo(row) {

      this.$modal.confirm('是否确认删除该新增区域商品').then(function() {

      }).then(() => {
        this.addInfoTabList = this.addInfoTabList.filter(item => { return item.newIndex != row.newIndex})
        this.addInfoList = this.addInfoList.filter(item => { return item.newIndex != row.newIndex})
        this.inputInfoList = this.addInfoTabList.concat(this.inputInfoListTemp);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 编辑经销商商品信息 */
    handleEditInputInfo(row){
      this.queryGoodsListParams.belongBusinessId = this.form.belongBusinessId
      this.updateAreaGoodsDoFlag = 1
      // 查询可选择的商品信息
      getGoodsInfoQuery(this.queryGoodsListParams).then(response => {
        const { data } = response
        const options = []
        const areaId = row.areaId
        // console.log(data)
        for(let i in data) {
          options.push({
            key: data[i].id,
            label: data[i].goodsName,
            disabled: false,
            ...data[i]
          });
        }
        // 每次打开之前都需要初始/重置一些参数
        this.inputCheckedAreaList = {
          commonSaleArea: row.saleArea
        };
        this.inputInfoOptions = options
        if(row.goodsId == '未选择'){
          this.inputCheckedIdList = [];
        }else{
          this.inputCheckedIdList = [row.gid];
          this.disabledSelectChange(this.inputCheckedIdList)
        }
        //this.inputInfoListTemp = data
        this.leftCurrentPage = 1
        this.rightCurrentPage = 1
        this.selectInputVisible = true
        this.addNewAreaGoodsEnable = false
        this.leftDefaultChecked = []
        this.rightDefaultChecked = []
        this.updateDealerGoodsId = row.id
      });
    },
    /** 编辑新增经销商商品信息 */
    handleEditNewInputInfo(row){
      this.updateAreaGoodsDoFlag = 1
      this.newIndex = row.newIndex
      this.queryGoodsListParams.belongBusinessId = this.form.belongBusinessId
      // 查询可选择的商品信息
      getGoodsInfoQuery(this.queryGoodsListParams).then(response => {
        const { data } = response;
        const options = [];
        // console.log(data)
        for(let i in data) {
          options.push({
            key: data[i].id,
            label: data[i].goodsName,
            ...data[i]
          });
        }
        // 每次打开之前都需要初始/重置一些参数
        this.inputCheckedAreaList = {commonSaleArea: [row.saleArea],commonSaleAreaId:row.areaId};
        this.inputInfoOptions = options;
        if(row.id == 0){
          this.inputCheckedIdList = [];
        }else{
          this.inputCheckedIdList = [row.id];
          this.disabledSelectChange(this.inputCheckedIdList)
        }
        //this.inputInfoListTemp = data;
        this.leftCurrentPage = 1;
        this.rightCurrentPage = 1;
        this.selectInputVisible = true;
        this.addNewAreaGoodsEnable = true
        this.leftDefaultChecked = [];
        this.rightDefaultChecked = [];
      });
    },
    /**
     *
     * @param {*} value 已选中的值[数组]
     * @param {*} direction 移动方向 left，right
     * @param {*} movedKeys 移动的key数组
     */
    handleSelectChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys);
      //进行商品信息编辑操作时，限制右侧只可以选择1个
      this.inputCheckedIdList = value;
      if(this.updateAreaGoodsDoFlag == 1 ){
        if(direction == 'right' && value.length >= 1){
          const selectedKey = value.map(item => item)
          this.inputInfoOptions.forEach(item => {
            if(!selectedKey.includes(item.key)){
              item.disabled = true
            }
          })
        }else if(direction == 'left'){
          this.inputInfoOptions.forEach(item => {
              item.disabled = false
          })
        }
      }
    },
    //进行商品信息编辑时，限制穿梭窗左侧选项为不可选
    disabledSelectChange(value){
      const selectedKey = value.map(item => item)
      this.inputInfoOptions.forEach(item => {
        if(!selectedKey.includes(item.key)){
          item.disabled = true
        }
      })
    },

    /*  左侧分页参数变化时  */
    // 由于vue双向绑定的一些机制，所以需要在这边给定一个方法让子组件调用并修改传入子组件的参数
    // 这里做同步修改之后，再次打开该弹窗时上面的重置数据才会被子组件监听到。。。
    // 当然如果嫌麻烦可以直接给dialog 加个if直接销毁
    handlePageChange(value, type) {
      if(type === 'left') {
        this.leftCurrentPage = value;
      } else {
        this.rightCurrentPage = value;
      }
    },

    transferLeftCheckChange(values) {
      this.leftDefaultChecked = values;
      //当进行编辑时禁用全选按钮
      if(this.leftDefaultChecked.length > 1 && this.updateAreaGoodsDoFlag == 1){
        this.leftDefaultChecked = this.leftDefaultChecked.map(item => !this.leftDefaultChecked.includes(item))
      }
    },

    transferRightCheckChange(values) {
      this.rightDefaultChecked = values;
    },

    renderTransferLabel(h, option) {
      return <div><span style='margin-left: 20px;'>{ option.label }</span><span style='margin: 0px 30px; color: #e6ebf5'>|</span><span>{ option.goodsId }</span></div>;
    },

    /** 打开新增经销商商品信息窗口 */
    openSelectInputDialog() {
      if(this.form.belongBusinessId == undefined || this.form.belongBusinessId == ''){
        this.$message.error('请先选择所属商户')
        // this.$modal.confirm('请先选择所属商户')
        return
      }

      this.queryGoodsListParams.belongBusinessId = this.form.belongBusinessId

      // 查询可选择的商品信息
      getGoodsInfoQuery(this.queryGoodsListParams).then(response => {
        const { data } = response;
        const options = [];
        // console.log(data)
        for(let i in data) {
          options.push({
            key: data[i].id,
            label: data[i].goodsName,
            ...data[i]
          });
        }
        // 每次打开之前都需要初始/重置一些参数
        this.inputCheckedAreaList = {commonSaleArea:'',commonSaleAreaId: undefined};
        this.inputInfoOptions = options;
        //this.inputInfoListTemp = data;
        this.leftCurrentPage = 1;
        this.rightCurrentPage = 1;
        this.inputCheckedIdList = [];
        this.leftDefaultChecked = [];
        this.rightDefaultChecked = [];
        this.selectInputVisible = true;
        this.addNewAreaGoodsEnable = true;
        this.updateAreaGoodsDoFlag = 0
      });
    },

    selectInputCancel() {
      this.selectInputVisible = false;
      this.resetTransferQuery();
    },

    resetTransferQuery() {
      // 执行子组件中的重置所有搜索框的方法
      this.$refs.inputTransfer.$emit("resetAllSearchInput")
    },

    submitSelectInput() {
      this.$refs['formSaleArea'].validate((valid) => {
        if (!valid) {
          return
        }
        this.selectInputVisible = false;
        // const addIdList = this.inputCheckedIdList.filter(item => !this.inputInfoIdList.includes(item));
        const addIdList = this.inputCheckedIdList;
        const addGoodList = this.inputInfoOptions.filter(item => addIdList.includes(item.key));
        if(this.form.dealerId == ' '){
          this.form.dealerId = null
        }
        if(addIdList.length > 0) {
          //新增区域商品
          // const selectedList = this.inputInfoListTemp.filter(item => this.inputCheckedIdList.includes(item.id));
          const addList = [];
          const goodsArea = this.inputCheckedAreaList.commonSaleArea;
          const addDealerGoodsLsit = [];
          for(let i = 0; i < addIdList.length; i++) {
            this.updateNewIndex = this.updateNewIndex+1;
            addList.push({
              // province:goodsArea[0],
              // city:goodsArea[1],
              // county:goodsArea[2],
              saleArea:goodsArea,
              inputsGoodsName:addGoodList[i].goodsName,
              areaId:this.inputCheckedAreaList.commonSaleAreaId,
              id:addGoodList[i].id,
              newIndex:this.updateNewIndex,
              newGoods:1
            });
            addDealerGoodsLsit.push({
              dealerId:this.form.dealerId,
              dealerName:this.form.dealerName,
              goodsId:addGoodList[i].goodsId,
              goodsName:addGoodList[i].goodsName,
              belongBusinessName:addGoodList[i].belongBusinessName,
              belongBusinessId:addGoodList[i].belongBusinessId,
              saleAreaId:this.inputCheckedAreaList.commonSaleAreaId,
              saleArea:goodsArea,
              newIndex:this.updateNewIndex
            })
          }
          if(this.newIndex != undefined){
            this.addInfoTabList = addList.concat(this.addInfoTabList.filter(item => { return item.newIndex != this.newIndex}));
            this.addInfoList = addDealerGoodsLsit.concat(this.addInfoList.filter(item => { return item.newIndex != this.newIndex}));
            // this.inputInfoList = this.inputInfoListTemp.concat(this.addInfoTabList);
            this.inputInfoList = this.addInfoTabList.concat(this.inputInfoListTemp);
            console.log("*****update1****")
            console.log( this.addInfoTabList)
            console.log("*********")
          }else{
            this.addInfoTabList = addList.concat(this.addInfoTabList.filter(item => { return item.newIndex != this.newIndex}));
            this.addInfoList = addDealerGoodsLsit.concat(this.addInfoList.filter(item => { return item.newIndex != this.newIndex}));
            this.inputInfoList = this.addInfoTabList.concat(this.inputInfoListTemp);
            console.log("*********")
            console.log( this.addInfoTabList)
            console.log("*********")
          }
          // 清空一次this.inputCheckedIdList 避免vue监听不到变化
          this.inputCheckedIdList = [];
        }else{
          const addList = [];
          const goodsArea = this.inputCheckedAreaList.commonSaleArea;
          const addDealerGoodsLsit = [];
          this.updateNewIndex = this.updateNewIndex+1;
          addList.push({
            // province:goodsArea[0],
            // city:goodsArea[1],
            // county:goodsArea[2],
            saleArea:goodsArea,
            inputsGoodsName:'未选择',
            areaId:this.inputCheckedAreaList.commonSaleAreaId,
            id:0,
            newGoods:1,
            newIndex:this.updateNewIndex
          });
          addDealerGoodsLsit.push({
            dealerId:this.form.dealerId,
            dealerName:this.form.dealerName,
            goodsId:'未选择',
            goodsName:'未选择',
            belongBusinessName:'未选择',
            belongBusinessId:this.form.belongBusinessId,
            saleAreaId:this.inputCheckedAreaList.commonSaleAreaId,
            saleArea:goodsArea,
            newIndex:this.updateNewIndex
          })
          this.addInfoTabList = addList.concat(this.addInfoTabList.filter(item => { return item.newIndex != this.newIndex}));
            this.addInfoList = addDealerGoodsLsit.concat(this.addInfoList.filter(item => { return item.newIndex != this.newIndex}));
            this.inputInfoList = this.addInfoTabList.concat(this.inputInfoListTemp);
            console.log("*****update0****")
            console.log( this.addInfoTabList)
            console.log("*********")
          // if(this.newIndex != undefined){
          //   this.addInfoTabList = addList.concat(this.addInfoTabList.filter(item => { return item.newIndex != this.newIndex}));
          //   this.addInfoList = addDealerGoodsLsit.concat(this.addInfoList.filter(item => { return item.newIndex != this.newIndex}));
          //   this.inputInfoList = this.addInfoTabList.concat(this.inputInfoListTemp);
          //   console.log("*****update0****")
          //   console.log( this.addInfoTabList)
          //   console.log("*********")
          // }else{
          //   this.addInfoTabList = addList.concat(this.addInfoTabList.filter(item => { return item.newIndex != this.newIndex}));
          //   this.addInfoList = addDealerGoodsLsit.concat(this.addInfoList.filter(item => { return item.newIndex != this.newIndex}));
          //   this.inputInfoList = this.addInfoTabList.concat(this.inputInfoListTemp);
          //   console.log("*********")
          //   console.log( this.addInfoTabList)
          //   console.log("*********")
          // }
          // 清空一次this.inputCheckedIdList 避免vue监听不到变化
          this.inputCheckedIdList = [];
        }
        this.newIndex = undefined
        if(this.aaddInfoTabVisible == false){
          this.aaddInfoTabVisible = true;
        }
      })
    },

    //更新已经在数据库中的经销商商品信息
    submitSelectUpdateInput() {
      this.$refs['formSaleArea'].validate((valid) => {
        if (!valid) {
          return
        }
        this.selectInputVisible = false;
        const addIdList = this.inputCheckedIdList;
        const addGoodList = this.inputInfoOptions.filter(item => addIdList.includes(item.key));
        if(addIdList.length > 0) {
          //更新区域商品
          const addList = [];
          const goodsArea = this.inputCheckedAreaList.commonSaleArea;
          const addDealerGoodsLsit = [];
          for(let i = 0; i < addIdList.length; i++) {
            addList.push({
              // province:goodsArea[0],
              // city:goodsArea[1],
              // county:goodsArea[2],
              saleArea:goodsArea,
              inputsGoodsName:addGoodList[i].goodsName,
              areaId:this.inputCheckedAreaList.commonSaleAreaId,
              goodsId:addGoodList[i].goodsId,
              id:this.updateDealerGoodsId,
              gid:addGoodList[i].id
            });
            addDealerGoodsLsit.push({
              dealerId:this.form.dealerId,
              dealerName:this.form.dealerName,
              goodsId:addGoodList[i].goodsId,
              goodsName:addGoodList[i].goodsName,
              belongBusinessName:addGoodList[i].belongBusinessName,
              belongBusinessId:addGoodList[i].belongBusinessId,
              saleAreaId:this.inputCheckedAreaList.commonSaleAreaId,
              saleArea:goodsArea,
              id:this.updateDealerGoodsId,
              //gid:addGoodList[i].id
            })
          }
          this.inputInfoList = addList.concat(this.inputInfoList.filter(item => { return item.id != this.updateDealerGoodsId}));
          this.addInfoUpdateList = addDealerGoodsLsit.concat(this.addInfoUpdateList.filter(item => { return item.id != this.updateDealerGoodsId}));
          // 清空一次this.inputCheckedIdList 避免vue监听不到变化
          this.inputCheckedIdList = [];
        }

      })
    },

    //经销商信息进行编辑时，更改所属商户下方所属商品信息动态变更
    businessIdChangeToSelectGooods(){
      //切换商户时清空之前的添加和修改的商品
      this.addInfoList = []
      this.addInfoTabList = []
      this.addInfoUpdateList = []
      if(this.form.dealerId == undefined){
        this.form.dealerId = " "
      }
      this.getDealerGoodsList(this.form.dealerId,this.form.belongBusinessId)
    },

    //父组件中获取地区组件传递参数方法
    getArea(val){
      this.form.commonSaleArea = val
    },
    getAreaId(val){
      this.form.commonSaleAreaId = val
    },
    getGoodsArea(val){
      this.inputCheckedAreaList.commonSaleArea = val
    },
    getGoodsAreaId(val){
      this.inputCheckedAreaList.commonSaleAreaId = val
    },
    //获取el-select选择的标签
    labelClick(data){
      this.form.belongBusinessName = data;
    },

  }
}
</script>
<style scoped lang="scss">
</style>
