<template>
  <div class="mainContent">
    <el-drawer :with-header="false" :size="1000" :visible.sync="drawer_show" direction="rtl" :before-close="closeEditInfo">
      <!-- 顶部标题 -->
      <div class="title">{{ page_title }}</div>
      <!-- 当前用户信息 -->
      <div class="current-user-info" v-if="info.uid > 0">
        <div class="top-user">
          <div class="user-content">
            <div class="user-avatar">
              <img :src="info.user.avatar || moren" />
            </div>
            <div class="user-info">
              <div class="nickname">
                {{ info.user.nickname }}
                <div class="user-id">{{info.uid}}</div>
              </div>
              <div class="user-address">
                <!--{{ info.province_name }}{{ info.city_name }}{{ info.area_name }}{{ info.street_name }}{{ info.address }}-->
              </div>
            </div>
          </div>
          <el-button size="small" type="warning" round @click="addChildren(1, true)">切换用户</el-button>
        </div>
        <div class="info-list">
          <el-form ref="editInfoField" size="small" :model="info" label-width="130px" @submit.native.prevent>
            <el-row>
              <!--公共内容-->
              <el-col :span="12">
                <el-form-item label="联系人姓名：" prop="contact_name">
                  <el-input v-model="info.contact_name" placeholder="请填写联系人姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人电话：" prop="contact_phone">
                  <el-input v-model="info.contact_phone" placeholder="请填写联系人电话" />
                </el-form-item>
              </el-col>
              <!--仅总部发起人-->
              <el-col :span="12" v-if="info.agent_type == 1">
                <el-form-item label="股份：">
                  <el-tooltip class="item" effect="dark" content="请在总部发起人管理中编辑股份信息！" placement="right">
                    <el-input :value="info.agent_stock" type="text" readonly />
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <!--是否为总部-->
              <!--<el-col :span="12" v-if="info.agent_type != 1">-->
              <!--  <el-form-item label="是否为总部：">-->
              <!--    <el-radio-group v-model="info.is_headquarters" type="button">-->
              <!--      <el-radio :label="0">不是</el-radio>-->
              <!--      <el-radio :label="1">是</el-radio>-->
              <!--    </el-radio-group>-->
              <!--  </el-form-item>-->
              <!--</el-col>-->
              <el-col :span="12" v-if="info.agent_type == 2 || info.agent_type == 5">
                <el-form-item label="公司名称：">
                  <el-input v-model="info.corporate_name" placeholder="请填写公司名称" />
                </el-form-item>
              </el-col>
              <!-- 地区选择，仅需要的显示  类型：1=总部发起人,2=省发起人,3=省公司外勤,4=省公司内勤,5=区县运营商,6=区县合伙人,7=餐厅,8=配送商  && info.is_headquarters == 0-->
              <el-col :span="24" v-if="['5','6','7'].includes(String(info.agent_type))">
                <el-form-item label="地区：">
                  <div class="selected-city">
                    <!--省选择-->
                    <area-info :area_id="info.province_id" class="selected-city-item" @change="changeAreaInfo($event,-1)"></area-info>
                    <!--市选择-->
                    <area-info
                      :area_id="info.city_id"
                      :pid="info.province_id"
                      class="selected-city-item"
                      v-if="['5','6','7'].includes(String(info.agent_type)) && Number(info.province_id) > 0"
                      @change="changeAreaInfo($event,-1)"
                    ></area-info>
                    <!--区/县选择-->
                    <area-info
                      :area_id="info.area_id"
                      :pid="info.city_id"
                      class="selected-city-item"
                      v-if="['5','6','7'].includes(String(info.agent_type)) && Number(info.city_id) > 0"
                      @change="changeAreaInfo($event,-1)"
                    ></area-info>
                    <!--镇/街道-->
                    <area-info
                      :area_id="info.street_id"
                      :pid="info.area_id"
                      class="selected-city-item"
                      v-if="['7'].includes(String(info.agent_type)) && Number(info.area_id) > 0"
                      @change="changeAreaInfo($event,-1)"
                    ></area-info>
                  </div>
                </el-form-item>
              </el-col>
              <!--省公司发起人 仅选择省-->
              <el-col :span="24" v-if="['2'].includes(String(info.agent_type))">
                <el-form-item label="地区：">
                  <div class="selected-city">
                    <!--省选择-->
                    <area-info :area_id="info.province_id" class="selected-city-item" @change="changeAreaInfo($event,-1)"></area-info>
                  </div>
                </el-form-item>
                <el-form-item label="关联省公司门店：">
                  <search-mer
                    :mer_id="info.mer_id"
                    :merchant_type="5"
                    @change="changeMer($event,-1)"
                    :selected_shop="selectedShop['mer'] || {}"
                    :agent_id="info.id || 0"
                  ></search-mer>
                </el-form-item>
              </el-col>
              <!-- 仅餐厅 显示详细地址、定位、商户关联（单个） && info.is_headquarters == 0 -->
              <template v-if="info.agent_type == 7">
                <el-col :span="24">
                  <el-form-item label="经纬度：" prop="lat">
                    <el-input :value="(info.lat || '') + ',' + (info.lng || '')" readonly enter-button="查找位置" style="width: 100%;" placeholder="请点击查找位置选择位置">
                      <el-button slot="append" type="primary" @click="searchPosition(-1)">查找位置</el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="详细地址：">
                    <el-input v-model="info.address" placeholder="请填写详细地址" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="关联商户：">
                    <search-mer
                      :mer_id="info.mer_id"
                      @change="changeMer($event,-1)"
                      :selected_shop="selectedShop['mer'] || {}"
                      :agent_id="info.id || 0"
                    ></search-mer>
                  </el-form-item>
                </el-col>
              </template>
              <!-- 仅配送商  显示商户关联（多个） && info.is_headquarters == 0-->
              <el-col :span="24" v-if="info.agent_type == 8">
                <el-form-item label="关联商户：">
                  <search-mer
                    :mer_id="info.mer_id_list"
                    :merchant_type="1"
                    @change="changeMer($event,-1)"
                    :is_multiple="true"
                    :selected_shop="selectedShop['shop_mer'] || {}"
                    :agent_id="info.id || 0"
                  ></search-mer>
                </el-form-item>
              </el-col>
              <!-- 仅烟酒馆  显示商户关联（多个）-->
              <el-col :span="24" v-if="info.agent_type == 11">
                <el-form-item label="关联商户：">
                  <search-mer
                    :mer_id="info.mer_id_list"
                    :merchant_type="3"
                    @change="changeMer($event,-1)"
                    :is_multiple="true"
                    :selected_shop="selectedShop['wine'] || {}"
                    :agent_id="info.id || 0"
                  ></search-mer>
                </el-form-item>
              </el-col>

            </el-row>
          </el-form>
        </div>
      </div>
      <!-- 下级信息/总部发起人信息 -->
      <div class="sub-list">
        <!-- 操作按钮 -->
        <el-button v-if="Number(agent_type) === 0" size="small" type="primary" @click="addChildren(1)">添加总部发起人</el-button>
        <el-button v-if="Number(agent_type) === 1" size="small" type="primary" @click="addChildren(9)">添加总部外勤</el-button>
        <el-button v-if="Number(agent_type) === 1" size="small" type="primary" @click="addChildren(10)">添加总部内勤</el-button>
        <el-button v-if="Number(agent_type) === 9" size="small" type="primary" @click="addChildren(2)">添加省发起人</el-button>
        <el-button v-if="Number(agent_type) === 2" size="small" type="primary" @click="addChildren(3)">添加省公司外勤</el-button>
        <el-button v-if="Number(agent_type) === 2" size="small" type="primary" @click="addChildren(4)">添加省公司内勤</el-button>
        <el-button v-if="Number(agent_type) === 3" size="small" type="primary" @click="addChildren(5)">添加区县运营商</el-button>
        <el-button v-if="Number(agent_type) === 5" size="small" type="primary" @click="addChildren(6)">添加区县合伙人</el-button>
        <el-button v-if="Number(agent_type) === 6" size="small" type="primary" @click="addChildren(7)">添加餐厅</el-button>
        <!--<el-button v-if="![0,4,7,8].includes(Number(agent_type))" size="small" type="warning" @click="addChildren(8)">添加配送商</el-button>-->
        <el-button v-if="Number(agent_type) === 6" size="small" type="warning" @click="addChildren(8)">添加配送商</el-button>
        <el-button v-if="![7,8,11].includes(Number(agent_type))" size="small" type="primary" @click="addChildren(11)">添加烟酒店代销商</el-button>
        <el-button size="small" type="success" @click="submitEditInfo">提交编辑</el-button>
        <el-button size="small" @click="closeEditInfo">取消编辑</el-button>
        <!-- 角色列表 -->
        <div class="role-list">
          <div class="role-block" v-for="(item,index) in children_list" :key="index">
            <div class="top-user-content">
              <div class="user-content">
                <div class="user-avatar">
                  <img :src="item.user.avatar || moren" />
                </div>
                <div class="user-info">
                  <div class="nickname">
                    {{ item.user.nickname }}
                    <div class="user-id">{{ item.user.uid }}</div>
                  </div>
                  <div class="agent-type-text">
                    <!--TODO：由于需要兼容添加时的初始数据 这里不能使用后台传递的角色类型 只能使用type进行判断-->
                    <el-tag v-if="Number(item.agent_type) == 1" type="info" effect="dark" size="small">总部发起人</el-tag>
                    <el-tag v-if="Number(item.agent_type) == 9" type="info" effect="dark" size="small">总部外勤</el-tag>
                    <el-tag v-if="Number(item.agent_type) == 10" type="info" effect="dark" size="small">总部内勤</el-tag>
                    <el-tag v-if="Number(item.agent_type) == 2" type="info" effect="dark" size="small">省发起人</el-tag>
                    <el-tag v-if="Number(item.agent_type) == 3" type="info" effect="dark" size="small">省公司外勤</el-tag>
                    <el-tag v-if="Number(item.agent_type) == 4" type="info" effect="dark" size="small">省公司内勤</el-tag>
                    <el-tag v-if="Number(item.agent_type) == 5" type="info" effect="dark" size="small">区县运营商</el-tag>
                    <el-tag v-if="Number(item.agent_type) == 6" type="info" effect="dark" size="small">区县合伙人</el-tag>
                    <el-tag v-if="Number(item.agent_type) == 7" type="info" effect="dark" size="small">餐厅</el-tag>
                    <el-tag v-if="Number(item.agent_type) == 8" type="info" effect="dark" size="small">配送商</el-tag>
                    <el-tag v-if="Number(item.agent_type) == 11" type="info" effect="dark" size="small">烟酒店代销商</el-tag>
                  </div>
                </div>
              </div>
              <div class="user-del-btn">
                <el-button type="danger" icon="el-icon-delete" circle @click="closeStaffConfirm(index)"></el-button>
              </div>
            </div>
            <div class="bottom-form-content">
              <el-form ref="editInfoField" size="small" :model="children_list" label-width="130px" @submit.native.prevent>
                <el-row>
                  <!-- 公共表单内容 -->
                  <el-col :span="12">
                    <el-form-item label="联系人姓名：" prop="contact_name">
                      <el-input v-model="children_list[index].contact_name" placeholder="请填写联系人姓名" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系人电话：" prop="contact_phone">
                      <el-input v-model="children_list[index].contact_phone" placeholder="请填写联系人电话" />
                    </el-form-item>
                  </el-col>
                  <!--<el-col :span="12">-->
                  <!--  <el-form-item label="是否为总部：">-->
                  <!--    <el-radio-group v-model="children_list[index].is_headquarters" type="button" :disabled="info.id > 0 && info.agent_type != 1">-->
                  <!--      <el-radio :label="0">不是</el-radio>-->
                  <!--      <el-radio :label="1">是</el-radio>-->
                  <!--    </el-radio-group>-->
                  <!--  </el-form-item>-->
                  <!--</el-col>-->
                  <el-col :span="12" v-if="children_list[index].agent_type == 2 || children_list[index].agent_type == 5">
                    <el-form-item label="公司名称：">
                      <el-input v-model="children_list[index].corporate_name" placeholder="请填写公司名称" />
                    </el-form-item>
                  </el-col>
                  <!-- 仅总部发起人显示 -->
                  <el-col :span="12" v-if="children_list[index].agent_type == 1">
                    <el-form-item label="股份：" prop="agent_stock">
                      <el-input v-model.number="children_list[index].agent_stock" type="number" step="0.01" placeholder="请填写该总部发起人股份" />
                    </el-form-item>
                  </el-col>
                  <!-- 地区选择，仅需要的显示  类型：1=总部发起人,2=省发起人,3=省公司外勤,4=省公司内勤,5=区县运营商,6=区县合伙人,7=餐厅,8=配送商  && children_list[index].is_headquarters == 0-->
                  <el-col :span="24" v-if="['5','6','7'].includes(String(children_list[index].agent_type))">
                    <el-form-item label="地区：">
                      <div class="selected-city">
                        <!--省选择-->
                        <area-info
                          :area_id="children_list[index].province_id"
                          class="selected-city-item"
                          @change="changeAreaInfo($event,index)"
                        ></area-info>
                        <!--市选择-->
                        <area-info
                          :area_id="children_list[index].city_id"
                          :pid="children_list[index].province_id"
                          class="selected-city-item"
                          v-if="['5','6','7'].includes(String(children_list[index].agent_type)) && Number(children_list[index].province_id) > 0"
                          @change="changeAreaInfo($event,index)"
                        ></area-info>
                        <!--区/县选择-->
                        <area-info
                          :area_id="children_list[index].area_id"
                          :pid="children_list[index].city_id"
                          class="selected-city-item"
                          v-if="['5','6','7'].includes(String(children_list[index].agent_type)) && Number(children_list[index].city_id) > 0"
                          @change="changeAreaInfo($event,index)"
                        ></area-info>
                        <!--镇/街道-->
                        <area-info
                          :area_id="children_list[index].street_id"
                          :pid="children_list[index].area_id"
                          class="selected-city-item"
                          v-if="['7'].includes(String(children_list[index].agent_type)) && Number(children_list[index].area_id) > 0"
                          @change="changeAreaInfo($event,index)"
                        ></area-info>
                      </div>
                    </el-form-item>
                  </el-col>
                  <!-- 省公司发起人 仅选择省 -->
                  <el-col :span="24" v-if="['2'].includes(String(children_list[index].agent_type))">
                    <el-form-item label="地区：">
                      <div class="selected-city">
                        <!--省选择-->
                        <area-info
                          :area_id="children_list[index].province_id"
                          class="selected-city-item"
                          @change="changeAreaInfo($event,index)"
                        ></area-info>
                      </div>
                    </el-form-item>
                    <el-form-item label="关联省公司门店：">
                      <search-mer
                        :mer_id="children_list[index].mer_id"
                        :merchant_type="5"
                        @change="changeMer($event,index)"
                        :selected_shop="selectedShop['mer'] || {}"
                        :agent_id="children_list[index].id || 0"
                      ></search-mer>
                    </el-form-item>
                  </el-col>
                  <!-- 仅餐厅 显示详细地址、定位、商户关联（单个）  && children_list[index].is_headquarters == 0-->
                  <template v-if="children_list[index].agent_type == 7">
                    <el-col :span="24">
                      <el-form-item label="经纬度：" prop="lat">
                        <el-input :value="(children_list[index].lat || '') + ',' + (children_list[index].lng || '')" readonly enter-button="查找位置" style="width: 100%;" placeholder="请点击查找位置选择位置">
                          <el-button slot="append" type="primary" @click="searchPosition(index)">查找位置</el-button>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="详细地址：">
                        <el-input v-model="children_list[index].address" placeholder="请填写详细地址" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="关联商户：">
                        <search-mer
                          :mer_id="children_list[index].mer_id"
                          @change="changeMer($event,index)"
                          :selected_shop="selectedShop['mer'] || {}"
                          :agent_id="children_list[index].id || 0"
                        ></search-mer>
                      </el-form-item>
                    </el-col>
                  </template>
                  <!-- 仅配送商  显示商户关联（多个） && children_list[index].is_headquarters == 0-->
                  <el-col :span="24" v-if="children_list[index].agent_type == 8">
                    <el-form-item label="关联商户：">
                      <search-mer
                        :mer_id="children_list[index].mer_id_list"
                        :merchant_type="1"
                        @change="changeMer($event,index)"
                        :is_multiple="true"
                        :selected_shop="selectedShop['shop_mer'] || {}"
                        :agent_id="children_list[index].id || 0"
                      ></search-mer>
                    </el-form-item>
                  </el-col>
                  <!-- 仅烟酒馆  显示商户关联（多个）-->
                  <el-col :span="24" v-if="children_list[index].agent_type == 11">
                    <el-form-item label="关联商户：">
                      <search-mer
                        :mer_id="children_list[index].mer_id_list"
                        :merchant_type="3"
                        @change="changeMer($event,index)"
                        :is_multiple="true"
                        :selected_shop="selectedShop['wine'] || {}"
                        :agent_id="children_list[index].id || 0"
                      ></search-mer>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
    <!------ 公共内容 ----------------------------------------------------->
    <!--用户选择-->
    <el-dialog :title="userSelectTitle" :visible.sync="userSelectVisible" width="80%" :before-close="closeStaff" :append-to-body="true">
      <el-card class="box-card">
        <!--顶部搜索栏-->
        <div slot="header" class="clearfix">
          <div class="container">
            <el-form inline size="small" label-width="80px">
              <el-form-item label="">
                <el-input v-model="userTableFrom.nickname" placeholder="请输入用户昵称" class="selWidth" clearable />
                <el-input v-model="userTableFrom.phone" placeholder="请输入用户手机号" class="selWidth" clearable />
                <el-input v-model="userTableFrom.uid" placeholder="请输入用户ID" class="selWidth" clearable>
                  <el-button slot="append" icon="el-icon-search" class="el-button-solt" @click="getUserList(1)" />
                </el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!--表格信息-->
        <el-table v-loading="userListLoading" :data="userTableData.data" :key="Object.values(children_uid_list).toString()" style="width: 100%" size="mini">
          <el-table-column label="用户信息" prop="nickname" min-width="300" align="center">
            <template slot-scope="scope">
              <div class="user-content">
                <div class="user-avatar">
                  <img :src="scope.row.avatar || moren" />
                </div>
                <div class="user-info">
                  <div class="nickname">{{ scope.row.nickname }}</div>
                  <div class="user-id">ID：{{ scope.row.uid }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="联系电话" prop="phone" min-width="150" align="center"/>
          <!--根据添加编辑类型 显示不同的内容-->
          <el-table-column v-if="Number(create_role_type) === 1" label="是否已成为总部发起人" min-width="200" align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="Object.values(children_uid_list).includes((String(scope.row.uid)+'_'+String(create_role_type)))" effect="dark">是</el-tag>
              <el-tag type="info" v-else effect="dark">不是</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="Number(create_role_type) === 2" label="是否已成为省发起人" min-width="200" align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="Object.values(children_uid_list).includes((String(scope.row.uid)+'_'+String(create_role_type)))" effect="dark">是</el-tag>
              <el-tag type="info" v-else effect="dark">不是</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="Number(create_role_type) === 3" label="是否已成为省公司外勤" min-width="200" align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="Object.values(children_uid_list).includes((String(scope.row.uid)+'_'+String(create_role_type)))" effect="dark">是</el-tag>
              <el-tag type="info" v-else effect="dark">不是</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="Number(create_role_type) === 4" label="是否已成为省公司内勤" min-width="200" align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="Object.values(children_uid_list).includes((String(scope.row.uid)+'_'+String(create_role_type)))" effect="dark">是</el-tag>
              <el-tag type="info" v-else effect="dark">不是</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="Number(create_role_type) === 5" label="是否已成为区县运营商" min-width="200" align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="Object.values(children_uid_list).includes((String(scope.row.uid)+'_'+String(create_role_type)))" effect="dark">是</el-tag>
              <el-tag type="info" v-else effect="dark">不是</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="Number(create_role_type) === 6" label="是否已成为区县合伙人" min-width="200" align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="Object.values(children_uid_list).includes((String(scope.row.uid)+'_'+String(create_role_type)))" effect="dark">是</el-tag>
              <el-tag type="info" v-else effect="dark">不是</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="Number(create_role_type) === 7" label="是否已成为餐厅" min-width="200" align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="Object.values(children_uid_list).includes((String(scope.row.uid)+'_'+String(create_role_type)))" effect="dark">是</el-tag>
              <el-tag type="info" v-else effect="dark">不是</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="Number(create_role_type) === 8" label="是否已成为配送商" min-width="200" align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="Object.values(children_uid_list).includes((String(scope.row.uid)+'_'+String(create_role_type)))" effect="dark">是</el-tag>
              <el-tag type="info" v-else effect="dark">不是</el-tag>
            </template>
          </el-table-column>
          <!--操作按钮-->
          <el-table-column label="操作" min-width="150" align="center">
            <template slot-scope="scope">
              <!--<el-button type="danger"  effect="dark" v-if="Object.values(children_uid_list).includes((String(scope.row.uid)+'_'+String(create_role_type)))" @click="closeStaffConfirm(scope.row.uid, create_role_type)">取消</el-button>-->
              <el-button type="success" effect="dark" @click="addStaffConfirm(scope.row)">添加</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div class="block">
          <el-pagination
            :page-sizes="[20, 40, 60, 80]"
            :page-size="userTableFrom.limit"
            :current-page="userTableFrom.page"
            layout="total, sizes, prev, pager, next, jumper"
            :total="userTableData.total"
            @size-change="handleUserSizeChange"
            @current-change="pageUserChange"
          />
        </div>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userSelectVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!--地图定位-->
    <el-dialog
      v-if="modalMap"
      v-model="modalMap"
      :visible.sync="modalMap"
      title="选择位置"
      close-on-click-modal
      class="mapBox"
      custom-class="dialog-scustom"
      :append-to-body='true'
      width="80%"
      top="20px"
    >
      <iframe id="mapPage" width="100%" height="700px" frameborder="0" :src="keyUrl" />
    </el-dialog>
  </div>
</template>

<script>
import areaInfo from './area';
import searchMer from './mer';
import {userLstApi} from "@/api/user";
import {getEditInfo, submitEditInfo} from "@/api/marketing";
import {configApi} from "@/api/system";

export default {
  props: {
    agent_type: {
      type: Number,
      default: 0
    },
    drawer_show: {
      type: Boolean,
      default: false
    },
    agent_id: {
      type: Number,
      default: 0
    },
  },
  components: {
    areaInfo,
    searchMer
  },
  data() {
    return {
      moren: require("@/assets/images/f.png"),
      page_title: '编辑信息',
      // 信息管理相关
      info: {},
      children_list: {},
      children_uid_list: {},
      // 用户选择弹框
      userSelectTitle: '用户选择',
      userSelectVisible: false,
      userListLoading: true,
      userTableFrom: {
        page: 1,
        limit: 20,
        nickname: '',
        phone: '',
        uid: ''
      },
      userTableData: {
        data: [],
        total: 0,
      },
      create_role_type: 0,
      is_change_user: false,
      // 定位相关
      modalMap: false,
      mapKey: '',
      keyUrl: '',
      delivery_type: '',
      current_handle_index: '',
      // 商户选择
      mer_loading: false,
      mer_list: {},
      selectedShop: {},// 已选择商户 mer=餐厅已选中，shop_mer=酒道馆已选中，wine=烟酒店已选中
    };
  },
  watch: {
    drawer_show: {
      handler: function () {
        // 信息初始化
        this.info = {};
        this.children_list = {};
        this.children_uid_list = {};
        if(this.drawer_show) this.getAgentEditInfo();
      },
    },
    agent_type: {
      handler: function () {
        // 类型：1=总部发起人,2=省发起人,3=省公司外勤,4=省公司内勤,5=区县运营商,6=区县合伙人,7=餐厅,8=配送商
        switch (Number(this.agent_type)) {
          case 0:
            this.page_title = '总部发起人管理';
            break;
          case 1:
            this.page_title = '总部发起人信息编辑';
            break;
          case 2:
            this.page_title = '省发起人信息编辑';
            break;
          case 3:
            this.page_title = '省公司外勤信息编辑';
            break;
          case 4:
            this.page_title = '省公司内勤信息编辑';
            break;
          case 5:
            this.page_title = '区县运营商信息编辑';
            break;
          case 6:
            this.page_title = '区县合伙人信息编辑';
            break;
          case 7:
            this.page_title = '餐厅信息编辑';
            break;
          case 8:
            this.page_title = '配送商信息编辑';
            break;
          case 9:
            this.page_title = '总部外勤信息编辑';
            break;
          case 10:
            this.page_title = '总部内勤信息编辑';
            break;
          case 11:
            this.page_title = '烟酒馆信息编辑';
            break;
        }
      },
      immediate: true
    },
    children_list: {
      handler: function () {
        this.children_uid_list = Object.values(this.children_list).map((item) => {
          return String(item.uid) + '_' + String(item.agent_type);
        });
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    window.addEventListener(
      'message',
      function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data
        if (loc && loc.module === 'locationPicker') {
          // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          window.parent.selectAddress(loc)
        }
      },
      false
    )
    window.selectAddress = this.selectAddress
    this.getMapKey();
  },
  methods: {
    // 初始化 - 获取当前需要修改的信息
    getAgentEditInfo(){
      let _this = this;
      let params = {
        agent_id: _this.agent_id,
      };
      getEditInfo(params).then((res) => {
        if(res.status == 200){
          let data = Object.assign({},res.data || {});
          _this.info = Object.assign({},data.info || {});
          _this.children_list = Object.assign({},data.children_list || {});
          _this.selectedShop.shop_mer = Object.assign({},data.shop_mer || {});
          _this.selectedShop.wine = Object.assign({},data.wine || {});
          _this.selectedShop.mer = Object.assign({},data.mer || {});
        }
      }).catch((res) => {
        _this.$message.error(res.message)
      })
    },
    // 用户选择器 - 弹框显示
    addChildren(create_role_type,is_change_user = false){
      this.getUserList(1);
      this.userSelectVisible = true;
      this.is_change_user = is_change_user;
      // 添加角色类型
      this.create_role_type = create_role_type || 0;
    },
    // 用户选择器 - 弹框关闭
    closeStaff() {
      this.userSelectVisible = false;
    },
    // 用户选择器 - 获取用户列表及分页相关
    getUserList(num) {
      let _this = this;
      this.userListLoading = true;
      this.userTableFrom.page = num ? num : this.userTableFrom.page;
      userLstApi(this.userTableFrom)
        .then((res) => {
          this.userTableData.data = res.data.list;
          this.userTableData.total = res.data.count;
          this.userListLoading = false;
        })
        .catch((res) => {
          this.userListLoading = false;
          this.$message.error(res.message);
        });
    },
    pageUserChange(page) {
      this.userTableFrom.page = page;
      this.getUserList('');
    },
    handleUserSizeChange(val) {
      this.userTableFrom.limit = val;
      this.getUserList('');
    },
    // 用户选择器 - 选中用户
    addStaffConfirm(item){
      if(this.is_change_user){
        this.info.uid = item.uid;
        this.info.user = item;
        this.closeStaff();
      }
      else{
        let nowTime = Date.now();
        let info = Object.assign({}, this.info);

        this.children_list[String(nowTime)] = {
          uid: item.uid,
          pid: info.id || 0,
          agent_type: this.create_role_type,
          agent_stock: 0,
          contact_name: item.real_name || item.nickname,
          contact_phone: item.phone || '',
          province_id: info.province_id || 0,
          city_id: info.city_id || 0,
          area_id: info.area_id || 0,
          street_id: info.street_id || 0,
          address: '',
          lat: '',
          lng: '',
          mer_id: '',
          mer_id_list: [],
          user: item,
          corporate_name: '',
        };
        this.children_list = Object.assign({}, this.children_list);
      }

      this.$forceUpdate();
    },
    // 用户选择器 - 删除用户
    closeStaffConfirm(index){
      // 判断：是否允许删除
      let childrenCount =  this.children_list[index].children_count || 0;
      if(Number(childrenCount) > 0){
        this.$message.error("存在下级信息，禁止删除！");
        return false;
      }
      // 删除操作
      delete this.children_list[index];
      this.children_list = Object.assign({}, this.children_list);
      this.$forceUpdate();
    },
    // 操作 - 取消编辑
    closeEditInfo(){
      this.$emit('closeEdit')
    },
    // 操作 - 提交编辑
    submitEditInfo(){
      let _this = this;
      let editInfo = Object.assign({},_this.info);
      editInfo.children_list = Object.assign({}, _this.children_list);
      let editInfoId = Number(editInfo.id || 0);
      let childrenListLen = Object.values(editInfo.children_list).length || 0;
      // 判断：如果 agent_type == 0 且children_list为空 则不允许提交，因为这时没有信息需要编辑
      if(Number(_this.agent_type) === 0 && childrenListLen <= 0){
        _this.$message.error("请至少添加一个总部发起人！")
        return false;
      }
      // 判断：editInfo不为空 且isSubmit=true   可以提交
      if((editInfoId > 0) || (editInfoId <= 0 && childrenListLen > 0)){
        submitEditInfo(editInfo).then((res) => {
          if(res.status == 200){
            _this.$message.success('操作成功');
            _this.closeEditInfo();
            _this.$forceUpdate();
          }
        }).catch((res) => {
          _this.$message.error(res.message)
        })
      }
    },
    // 地区选择器 - 切换地区
    changeAreaInfo(event,index){
      let _this = this;
      switch (event.type){
        case 'province':
          if(index == -1){
            _this.info.province_id = event.id;
            _this.info.city_id = 0;
            _this.info.area_id = 0;
            _this.info.street_id = 0;
          }else{
            _this.children_list[index].province_id = event.id;
            _this.children_list[index].city_id = 0;
            _this.children_list[index].area_id = 0;
            _this.children_list[index].street_id = 0;
          }
          break;
        case 'city':
          if(index == -1){
            _this.info.city_id = event.id;
            _this.info.area_id = 0;
            _this.info.street_id = 0;
          }else {
            _this.children_list[index].city_id = event.id;
            _this.children_list[index].area_id = 0;
            _this.children_list[index].street_id = 0;
          }
          break;
        case 'area':
          if(index == -1){
            _this.info.area_id = event.id;
            _this.info.street_id = 0;
          }else {
            _this.children_list[index].area_id = event.id;
            _this.children_list[index].street_id = 0;
          }
          break;
        case 'street':
          if(index == -1){
            _this.info.street_id = event.id;
          }else {
            _this.children_list[index].street_id = event.id;
          }
        break;
      }
      _this.$forceUpdate();
    },
    // 定位处理 - 获取地图key
    getMapKey() {
      configApi().then(res => {
        this.mapKey = res.data.tx_map_key
        const keys = res.data.tx_map_key
        this.keyUrl = `https://apis.map.qq.com/tools/locpicker?type=1&key=${keys}&referer=myapp`
        this.delivery_type = res.data.delivery_type
      }).catch(res => {
        this.$message.error(res.message)
      })
    },
    // 定位处理 - 定位处理
    searchPosition(index) {
      this.current_handle_index = index;
      if (!this.mapKey || this.mapKey == '') this.$message.error('平台未配置腾讯地图KEY')
      else this.modalMap = true
    },
    // 定位处理 - 选择经纬度
    selectAddress(data) {
      let index = this.current_handle_index;
      if(index == -1){
        this.info.lat = data.latlng.lat
        this.info.lng = data.latlng.lng
        this.info.address = data.poiaddress || ''
      }else{
        this.children_list[index].lat = data.latlng.lat
        this.children_list[index].lng = data.latlng.lng
        this.children_list[index].address = data.poiaddress || ''
      }

      this.modalMap = false
      this.$forceUpdate();
    },
    // 选择商户 - 商户改变
    changeMer(event,index){
      let _this = this;
      // 当前代理选中商户信息变更
      if(index == -1){
        let agent_type = _this.info.agent_type;
        if(agent_type == 7 || agent_type == 2) _this.info.mer_id = event.mer_id;
        else if(agent_type == 8 || agent_type == 11) _this.info.mer_id_list = event.event || [];
      }else{
        let agent_type = _this.children_list[index].agent_type;
        if(agent_type == 7 || agent_type == 2) _this.children_list[index].mer_id = event.mer_id;
        else if(agent_type == 8 || agent_type == 11) _this.children_list[index].mer_id_list = event.event || [];
      }

      _this.changeSelectedShop(index);
      _this.$forceUpdate();
    },
    // 改变酒道馆已选择商户
    changeSelectedShop(index){
      let _this = this;
      // 获取当前代理
      let currentAgent = _this.info
      if(index >= 0) currentAgent = _this.children_list[index] || {};
      // 获取对应的键  及变更后已选中内容
      let agentType = currentAgent.agent_type || 0;
      let selectedMerIds = {};// 当前代理已选中商户ID列表
      let keyName = '';
      if(agentType == 7 || agentType == 2){
        // 餐厅绑定商户变更
        selectedMerIds = Number(currentAgent.mer_id) > 0 ? [currentAgent.mer_id] : {};
        keyName = 'mer';
      }else if(agentType == 8 || agentType == 11){
        // 配送商 || 烟酒店代销商 绑定商户变更
        selectedMerIds = currentAgent.mer_id_list || {};
        keyName = agentType == 8 ? 'shop_mer' : 'wine';
      }
      // 执行删除 —— 循环对应已选中商户列表   进行对应的判断
      let selectedShop = Object.assign({}, _this.selectedShop[keyName] || {});
      let selectedShopMerIds = [];// 全部同类型代理已选中商户
      Object.values(selectedShop).forEach(function (item, index) {
        if(item.agent_id == currentAgent.id && !Object.values(selectedMerIds).includes(item.mer_id)){
          // 是当前代理操作   判断是否存在  不存在直接删除
          delete selectedShop[index];
        }else{
          selectedShopMerIds.push(item.mer_id);
        }
      })
      // 执行添加 —— 循环当前代理已选中数据  和所有已选中对比，不存在则添加
      selectedShop = Object.values(selectedShop);
      Object.values(selectedMerIds).forEach(function (merId) {
        if(!Object.values(selectedShopMerIds).includes(merId)){
          // 不存在所有已选中列表中   添加数据
          selectedShop.push({
            agent_id: currentAgent.id,
            contact_name: currentAgent.contact_name || '',
            mer_id: merId
          });
        }
      })
      selectedShop = Object.values(selectedShop);

      _this.$set(_this.selectedShop, keyName, Object.assign({}, selectedShop));
    }






  },
};
</script>

<style lang="scss" scoped>
.mainContent{
  // 顶部标题
  .title{
    padding: 20px 20px 10px;
    font-weight: 700;
    background-color: #f5f7fa;
    border-bottom: 1px solid #dfe4ed;
  }
  // 当前用户信息
  .current-user-info{
    padding: 20px;
    border-bottom: 1px solid #dfe4ed;
    .top-user{
      display: inline-flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      .user-content{
        margin-right: 30px;
        .nickname{
          height: 25px;
          line-height: 25px;
          font-size: 16px;
          color: #282828;
          display: inline-flex;
          flex-direction: row;
          flex-wrap: nowrap;
          justify-content: flex-start;
          align-items: center;
          .user-id{
            color: #fff;
            background-color: #409eff;
            border-color: #409eff;
            height: 18px;
            line-height: 20px;
            font-size: 13px;
            padding: 0 5px;
            border-radius: 5px;
            margin-left: 10px;
            width: max-content!important;
          }
        }
        .user-address{
          height: 25px;
          line-height: 25px;
          width: 100%;
          font-size: 13px;
          color: #606266;
        }
      }
    }
  }
  // 下级信息/总部发起人信息
  .sub-list{
    padding: 20px;
    .role-list{
      width: 100%;
      padding: 15px 0;
      display: inline-flex;
      flex-direction: column;
      flex-wrap: nowrap;
      align-items: flex-start;
      justify-content: center;
      .role-block{
        border: 1px solid #dfe4ed;
        width: 100%;
        border-radius: 5px;
        padding: 10px;
        .top-user-content{
          width: 100%;
          display: inline-flex;
          flex-direction: row;
          flex-wrap: nowrap;
          justify-content: space-between;
          align-items: center;
          .user-content{
            width: 300px;
            height: 80px!important;
            .user-info{
              height: 80px;
              display: inline-flex;
              flex-direction: column;
              flex-wrap: nowrap;
              align-items: flex-start;
              justify-content: space-evenly;
              .nickname{
                height: 25px;
                line-height: 25px;
                font-size: 16px;
                color: #282828;
                display: inline-flex;
                flex-direction: row;
                flex-wrap: nowrap;
                justify-content: flex-start;
                align-items: center;
                .user-id{
                  color: #fff;
                  background-color: #409eff;
                  border-color: #409eff;
                  height: 18px;
                  line-height: 20px;
                  font-size: 13px;
                  padding: 0 5px;
                  border-radius: 5px;
                  margin-left: 10px;
                  width: max-content!important;
                }
              }
            }
          }
          .user-del-btn{}
        }
        .bottom-form-content{
          margin-top: 10px;
          width: 100%;
        }
      }
      .role-block:not(:last-child){
        margin-bottom: 15px;
      }
    }
  }
}
.selected-city{
  display: inline-flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: nowrap;
  width: 100%;
  .selected-city-item{
    width: calc((100% - 20px) / 3);
  }
  .selected-city-item:not(:last-child){
    margin-right: 10px;
  }
}
.user-content{
  --user-content-height-: 80px;

  height: var(--user-content-height-);
  width: 100%;
  display: inline-flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
  .user-avatar{
    height: var(--user-content-height-);
    width: var(--user-content-height-);
    display: inline-flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: center;
    align-items: center;
    img{
      height: 80%!important;
      width: 80%!important;
      border-radius: 50% !important;
    }
  }
  .user-info{
    width: calc(100% - var(--user-content-height-));
    height: var(--user-content-height-);
    display: inline-flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: center;
    align-items: flex-start;
    .nickname{
      width: 100%;
      height: 25px;
      line-height: 25px;
      text-align: left;
      font-size: 15px;
      font-weight: bold;
      line-height: calc(var(--user-content-height- * 65%));
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .user-id{
      width: 100%;
      text-align: left;
      font-size: 13px;
      line-height: calc(var(--user-content-height- * 35%));
    }
  }
}
</style>
