<template>
  <div class="app-container">
    <el-descriptions class="margin-top" style="font-size: 1.2em;">
      <el-descriptions-item label="用户总数" label-style="border-left: solid 2px #419EFF;">{{
          count.userNum
        }}
      </el-descriptions-item>
      <el-descriptions-item label="已注册用户" label-style="border-left: solid 2px #419EFF;">{{
          count.userRegisterNum
        }}
      </el-descriptions-item>
      <el-descriptions-item label="已绑定仪器用户数" label-style="border-left: solid 2px #419EFF;">
        {{ count.userDeviceNum }}
      </el-descriptions-item>
    </el-descriptions>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="queryParams.userType" @keyup.enter.native="handleQuery" style="width: 50%">
          <el-option label="全部" :value="null"></el-option>
          <el-option label="会员" :value="1"></el-option>
          <el-option label="游客" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="会员昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入单个会员昵称进行搜索"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-popover placement="top-start" width="200" trigger="click"
                  content="手机号码和用户编号，满足其中之一内容即可">
        <el-form-item label="手机号码" prop="mobile" slot="reference">
          <el-input
            v-model="queryParams.mobile"
            placeholder="搜索多个请用英文逗号隔开"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-popover>
      <el-popover placement="top-start" width="200" trigger="click"
                  content="手机号码和用户编号，满足其中之一内容即可">
        <el-form-item label="用户编号" prop="id" slot="reference">
          <el-input
            v-model="queryParams.id"
            placeholder="搜索多个请用英文逗号隔开"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-popover>
      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          clearable
          v-model="queryParams.birthday"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择生日">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="省" prop="provinceId">
        <el-select v-model="queryParams.provinceId" @change="getCityList(queryParams.provinceId)" placeholder="请选择省"
                   @keyup.enter.native="handleQuery" filterable clearable @clear="clearOption(1)">
          <el-option
            v-for="item in provinceList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="市" prop="cityId">
        <el-select v-model="queryParams.cityId" @change="getAreaByPid(queryParams.cityId)" @clear="clearOption(2)"
                   @keyup.enter.native="handleQuery" filterable clearable placeholder="请选择市">
          <el-option
            v-for="item in cityList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区" prop="areaId">
        <el-select v-model="queryParams.areaId" @keyup.enter.native="handleQuery" filterable clearable
                   placeholder="请选择区">
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户注册时间" prop="createTime">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          end-placeholder="结束日期"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="仪器绑定" prop="devicesTags">
        <el-select v-model="queryParams.devicesIdList" multiple placeholder="请选择">
          <el-option
            v-for="item in deviceList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="仪器数量" prop="credit">
        <el-input-number :min="0" :precision="0" v-model="queryParams.deviceNumStart"
                         @keyup.enter.native="handleQuery"></el-input-number>
        至
        <el-input-number :min="0" :precision="0" v-model="queryParams.deviceNumEnd"
                         @keyup.enter.native="handleQuery"></el-input-number>
      </el-form-item>
      <el-form-item label="积分范围" prop="credit">
        <el-input-number :min="0" :precision="0" v-model="queryParams.creditStart"
                         @keyup.enter.native="handleQuery"></el-input-number>
        至
        <el-input-number :min="0" :precision="0" v-model="queryParams.creditEnd"
                         @keyup.enter.native="handleQuery"></el-input-number>
      </el-form-item>
      <!--      <el-form-item label="购买渠道" prop="purchaseChannels">-->
      <!--        <el-select v-model="queryParams.purchaseChannels" multiple placeholder="请选择">-->
      <!--          <el-option-->
      <!--            v-for="item in purchaseChannels"-->
      <!--            :key="item.value"-->
      <!--            :label="item.label"-->
      <!--            :value="item.value">-->
      <!--          </el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-popover placement="top-start" width="200" trigger="click"
                  content="外部标签和小程序标签，同时满足所选内容">
        <el-form-item label="外部标签" prop="wecomTags" slot="reference">
          <el-select v-model="queryParams.wecomTags" multiple placeholder="请选择">
            <el-option
              v-for="item in wecomTags"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-popover>
      <el-popover placement="top-start" width="200" trigger="click"
                  content="外部标签和小程序标签，同时满足所选内容">
        <el-form-item label="小程序标签" prop="miniProgramTags" slot="reference">
          <el-select v-model="queryParams.miniProgramTags" multiple placeholder="请选择">
            <el-option
              v-for="item in miniProgramTags"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-popover>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 批量操作下拉选项   -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-select v-model="batchOperateValue" placeholder="批量操作" size="mini" clearable>
          <el-option label="批量添加小程序标签" :value="1"></el-option>
          <el-option label="批量删除小程序标签" :value="2"></el-option>
          <el-option label="全量添加小程序标签" :value="3"></el-option>
          <el-option label="全量删除小程序标签" :value="4"></el-option>
          <el-option label="批量加减积分" :value="5"></el-option>
          <el-option label="全量加减积分" :value="6"></el-option>
          <el-option label="批量发送话术" :value="7"></el-option>
          <el-option label="全量发送话术" :value="8"></el-option>
          <el-option label="批量备注" :value="9"></el-option>
          <el-option label="全量备注" :value="10"></el-option>
          <el-option label="注销账号" :value="11"></el-option>
          <el-option label="导出数据" :value="12"></el-option>
          <el-option label="导出全量数据" :value="13"></el-option>
        </el-select>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-warning"
          size="mini"
          @click="batchOperate()"
        >确认
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 显示表格   -->
    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column fixed="left" type="selection" width="55" align="center"/>
      <el-table-column label="头像" align="center">
        <template slot-scope="scope">
          <el-avatar shape="circle" :size="50" :src="scope.row.headimg"/>
        </template>
      </el-table-column>
      <el-table-column label="会员昵称" align="center" prop="nickname"/>
      <el-table-column label="用户编号" align="center" prop="id"/>
      <el-table-column label="手机号码" align="center" prop="mobile" width="120px"/>
      <el-table-column label="生日" align="center" prop="birthday" width="120px"/>
      <el-table-column label="地区" align="center" prop="province" width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.province }}</span><br/>
          <span>{{ scope.row.city }}</span><br/>
          <span>{{ scope.row.area }}</span>
        </template>
      </el-table-column>
      <el-table-column label="信息完善" align="center" prop="isCompleteInformation">
        <template slot-scope="scope">
          <span style="color: red" v-show="scope.row.isCompleteInformation == 0">未完善</span>
          <span v-show="scope.row.isCompleteInformation == 1">已完善</span>
        </template>
      </el-table-column>
      <el-table-column label="用户注册时间" align="center" prop="createTime" width="200px"/>
      <el-table-column label="仪器" align="center" prop="devicesNum">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="viewUserInstrumentDetail(scope.row)">
            {{ scope.row.devicesNum }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="小程序标签" align="center" prop="miniProgramTags" width="150px">
        <template slot-scope="scope">
          <el-tag v-for="item in scope.row.miniProgramTags" :key="item.id">
            {{ item.tagName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="外部标签" align="center" prop="wecomTags" width="150px">
        <template slot-scope="scope">
          <el-tag v-for="item in scope.row.wecomTags" :key="item.id">
            {{ item.tagName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否对接" align="center" prop="is_abutment">
        <template slot-scope="scope">
          <span v-show="scope.row.isAbutment == 1">未对接</span>
          <span v-show="scope.row.isAbutment == 2">已对接</span>
          <span v-show="scope.row.isAbutment == 3">对接失败</span>
        </template>
      </el-table-column>
      <el-table-column label="积分" align="center" prop="credit">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="viewUserIntegralDetail(scope.row)">
            {{ scope.row.credit }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="即将过期积分" align="center" prop="expireCredit"/>
      <el-table-column label="用户类型" align="center" prop="userType">
        <template slot-scope="scope">
          <span v-show="scope.row.userType == 0">游客</span>
          <span v-show="scope.row.userType == 1">会员</span>
        </template>
      </el-table-column>
      <el-table-column label="unionid" align="center" prop="unionid"/>
      <el-table-column label="用户权限" align="center" prop="">
        <template slot-scope="scope">
          <span v-show="scope.row.clock == 1">开启打卡</span>
          <span v-show="scope.row.clock == 2">禁止打卡</span>
          <span v-show="scope.row.activity == 1">开启活动</span>
          <span v-show="scope.row.activity == 2">禁止活动</span>
        </template>
      </el-table-column>
      <el-table-column label="消息列表" align="center" prop="">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="viewMessageDetail(scope.row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['system:member:edit']">查看
          </el-button>
          <el-button v-if="scope.row.clock == 1" size="mini" type="text" @click="openOrCloseClock(scope.row)">禁止打卡
          </el-button>
          <el-button v-if="scope.row.clock == 2" size="mini" type="text" @click="openOrCloseClock(scope.row)">开启打卡
          </el-button>
          <el-button v-if="scope.row.activity == 1" size="mini" type="text" @click="openOrCloseActivity(scope.row)">
            禁止活动
          </el-button>
          <el-button v-if="scope.row.activity == 2" size="mini" type="text" @click="openOrCloseActivity(scope.row)">
            开启活动
          </el-button>
          <el-button size="mini" type="text" @click="informationSynchronization(scope.row)">个人信息同步</el-button>
          <el-button size="mini" type="text" @click="integralSynchronization(scope.row)">积分同步</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-dialog width="30%" title="修改用户备注" :visible.sync="editRemarkVisible" append-to-body>
        <el-form ref="form" :model="editRemarkForm" label-width="50px">
          <el-form-item label="备注 " prop="content">
            <el-input v-model="editRemarkForm.content" type="textarea" placeholder="请输入备注" show-word-limit
                      minlength="1"
                      maxlength="100"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="ocEditRemarkDialog()">关 闭</el-button>
          <el-button type="primary" @click="submitEditRemark()">确 定</el-button>
        </div>
      </el-dialog>
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="头像" prop="headimg">
          <el-avatar shape="circle" :size="50" :src="form.headimg"/>
        </el-form-item>
        <el-form-item label="会员昵称" prop="nickname" style="width: 44%">
          <el-input v-model="form.nickname" placeholder="请输入昵称"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile" style="width: 44%">
          <el-input v-model="form.mobile" placeholder="请输入手机"/>
        </el-form-item>
        <el-form-item label="用户编号" prop="id">
          <span>{{ form.id }}</span>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker clearable
                          v-model="form.birthday"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择生日">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否完善" prop="isCompleteInformation">
          <template slot-scope="scope">
            <span v-show="form.isCompleteInformation == 0">未完善</span>
            <span v-show="form.isCompleteInformation == 1">完善</span>
          </template>
        </el-form-item>
        <el-form-item label="省" prop="provinceId" style="width: 40%">
          <el-select v-model="form.provinceId" @change="getSaveCityList(form.provinceId)" @clear="clearSaveOption(1)"
                     filterable clearable placeholder="请选择省">
            <el-option
              v-for="item in provinceList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="cityId" style="width: 40%">
          <el-select v-model="form.cityId" @change="getSaveAreaByPid(form.cityId)" @clear="clearSaveOption(2)"
                     filterable clearable placeholder="请选择市">
            <el-option
              v-for="item in saveCityList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区" prop="areaId" style="width: 40%">
          <el-select v-model="form.areaId" filterable clearable placeholder="请选择区">
            <el-option
              v-for="item in saveAreaList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小程序标签" prop="tagIdArray" style="width: 80%">
          <treeselect v-model="form.miniProgramTags" :options="miniProgramTagTree" :multiple="true" :show-count="true"
                      placeholder="请选择小程序标签" :disable-branch-nodes="true"/>
        </el-form-item>
        <el-form-item label="外部标签" prop="tagIdArray" style="width: 80%">
          <treeselect v-model="form.wecomTags" :options="wecomTagTree" :multiple="true" :show-count="true"
                      placeholder="请选择外部标签" :disable-branch-nodes="true"/>
        </el-form-item>
        <el-form-item label="注册时间" prop="createTime">
          <el-date-picker v-model="form.createTime" readonly disabled type="date" value-format="yyyy-MM-dd"/>
        </el-form-item>
        <el-form-item label="积分" prop="credit">
          <span>{{ form.credit }}</span>
        </el-form-item>
        <el-form-item label="打卡状态" prop="clock">
          <el-select v-model="form.clock" style="width: 20%">
            <el-option label="开启打卡" :value="1"></el-option>
            <el-option label="禁止打卡" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参与活动状态" prop="activity">
          <el-select v-model="form.activity" style="width: 20%">
            <el-option label="开启参与" :value="1"></el-option>
            <el-option label="禁止参与" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注列表" prop="remark">
          <el-table :data="form.wxUserRemarkList" style="width: 100%">
            <el-table-column prop="id" label="序号" style="width: 10%"/>
            <el-table-column prop="content" label="备注内容" style="width: 60%"/>
            <el-table-column prop="createTime" label="创建时间" style="width: 30%"/>
            <el-table-column prop="createTime" label="操作" style="width: 10%">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="ocEditRemarkDialog(scope.row)">编辑
                </el-button>
                <el-button size="mini" type="text" icon="el-icon-edit" @click="submitDelRemark(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 小程序标签批量操作   -->
    <el-dialog :title="title" :visible.sync="batchMiniProgramVisible" width="50%"
               :before-close="cancelMiniProgramDialog">
      <el-form ref="miniProgramForm" :model="miniProgramForm" :rules="batchMiniProgramRules" label-width="150px">
        <el-row>
          <el-col :span="100">
            <el-form-item label="小程序标签" prop="tagIdArray" label-width="100px">
              <treeselect v-model="miniProgramForm.tagIdArray" :options="chatTagOptions" :multiple="true"
                          :show-count="true"
                          placeholder="请选择小程序标签" :disable-branch-nodes="true"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelMiniProgramDialog(false)">重 置</el-button>
        <el-button type="primary" @click="submitBatchOperate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 积分批量操作   -->
    <el-dialog :title="title" :visible.sync="batchIntegralVisible" width="50%" :before-close="cancelIntegralDialog">
      <el-form :model="integralForm" ref="integralForm" :rules="batchIntegralRules" label-width="150px">
        <el-form-item label="类型" prop="source">
          <el-select v-model="integralForm.source" style="width: 50%">
            <el-option label="增加" :value="1"></el-option>
            <el-option label="减少" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="变动积分" prop="floatScore">
          <el-input-number v-model="integralForm.floatScore" controls-position="right" :min="1"
                           :max="1000"></el-input-number>
        </el-form-item>
        <el-form-item label="说明 " prop="remarkContent">
          <el-input v-model="integralForm.remarkContent"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelIntegralDialog(false)">重 置</el-button>
        <el-button type="primary" @click="submitBatchOperate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 备注批量操作   -->
    <el-dialog :title="title" :visible.sync="batchRemarkVisible" width="50%" :before-close="cancelRemarkDialog">
      <el-form ref="remarkForm" :model="remarkForm" :rules="batchRemarkRules" label-width="150px">
        <el-form-item label="备注 " prop="content">
          <el-input v-model="remarkForm.content" type="textarea" placeholder="请输入备注" show-word-limit minlength="1"
                    maxlength="100"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRemarkDialog(false)">重 置</el-button>
        <el-button type="primary" @click="submitBatchOperate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 话术批量操作 -->
    <el-dialog :title="title" :visible.sync="batchScriptVisible" width="600px" append-to-body
               :before-close="cancelScriptDialog">
      <el-form ref="scriptForm" :model="scriptForm" :rules="batchScriptRules" label-width="150px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="类型" prop="isCustom">
              <el-select v-model="scriptForm.isCustom" @change="clearScript">
                <el-option label="话术模板发送" :value="0" :key="0"></el-option>
                <el-option label="自定义发送" :value="1" :key="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!--  话术模板发送      -->
        <el-row v-if="scriptForm.isCustom == 0">
          <el-col :span="40">
            <el-form-item label="话术二级标题选择" prop="scriptTemplateId">
              <treeselect v-model="scriptForm.scriptTemplateId" :options="scriptOptions" :show-count="true"
                          @select="selectTree"
                          placeholder="请选择话术" :disable-branch-nodes="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="40">
            <el-form-item label="话术通知内容" prop="scriptContent">
              <el-input v-model="scriptForm.scriptContent" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <!--  自定义发送      -->
        <el-row v-if="scriptForm.isCustom == 1">
          <el-col :span="24">
            <el-form-item label="话术标题" prop="titile">
              <el-input v-model="scriptForm.titile" placeholder="请输入话术标题" show-word-limit minlength="1"
                        maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="话术内容" prop="content">
              <el-input v-model="scriptForm.content" type="textarea" placeholder="请输入话术内容" show-word-limit
                        minlength="1" maxlength="500"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="小程序标签" prop="tagIdArray" label-width="90px">
              <treeselect v-model="scriptForm.tagIds" :options="chatTagOptions" :multiple="true" :show-count="true"
                          placeholder="请选择小程序标签" :disable-branch-nodes="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="跳转类型" prop="type">
              <el-select v-model="scriptForm.type">
                <el-option label="无跳转" :value="0" :key="0"></el-option>
                <el-option label="跳转内部链接" :value="1" :key="1"></el-option>
                <el-option label="跳转小程序" :value="4" :key="4"></el-option>
                <el-option label="跳转外部链接" :value="3" :key="3"></el-option>
                <el-option label="导向视频号" :value="5" :key="5"></el-option>
                <el-option label="导向视频号直播间" :value="6" :key="6"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="scriptForm.type == 1">
            <el-form-item label="内部链接" prop="link">
              <el-input v-model="scriptForm.link" placeholder="请输入内部链接"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="scriptForm.type == 1">
            <el-form-item label="跳转参数" prop="linkParams">
              <el-input v-model="scriptForm.linkParams" placeholder="请输入跳转参数"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="scriptForm.type == 3">
            <el-form-item label="外部链接" prop="link">
              <el-input v-model="scriptForm.link" placeholder="请输入外部链接"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="scriptForm.type == 4">
            <el-form-item label="小程序APPID" prop="redirectAppid">
              <el-input v-model="scriptForm.redirectAppid" placeholder="请输入APPID"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="scriptForm.type == 4" label-width="90px">
            <el-form-item label="小程序页面" prop="redirectUrl">
              <el-input v-model="scriptForm.redirectUrl" placeholder="请输入小程序页面"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="scriptForm.type == 5 || scriptForm.type == 6">
            <el-form-item label="视频号ID" prop="videoNo">
              <el-input v-model="scriptForm.videoNo" placeholder="视频号id，以“sph”开头的id，可再视频号助手获取"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="scriptForm.type == 5" label-width="90px">
            <el-form-item label="feedId" prop="feedId">
              <el-input v-model="scriptForm.feedId" placeholder="请输入视频号feedId"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchOperate">确 定</el-button>
        <el-button @click="cancelScriptDialog(false)">重 置</el-button>
      </div>
    </el-dialog>

    <!-- 查看用户消息列表   -->
    <el-dialog title="消息记录" :visible.sync="userScriptLogVisible" width="90%"
               :before-close="cancelUserScriptLogDialog">
      <template>
        <el-table :data="userScriptLogQuery.userScriptList" :stripe="true" style="width: 100%">
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column prop="messageType" label="消息类型" width="100px">
            <template slot-scope="scope">
              <span v-show="scope.row.messageType == 0">未知</span>
              <span v-show="scope.row.messageType == 1">用户注册</span>
              <span v-show="scope.row.messageType == 2">绑定仪器</span>
              <span v-show="scope.row.messageType == 3">打卡活动</span>
              <span v-show="scope.row.messageType == 4">护理计划</span>
              <span v-show="scope.row.messageType == 5">问卷活动</span>
              <span v-show="scope.row.messageType == 6">会员管理</span>
              <span v-show="scope.row.messageType == 7">消息模板</span>
              <span v-show="scope.row.messageType == 8">用户留言</span>
              <span v-show="scope.row.messageType == 9">完善用户信息</span>
            </template>
          </el-table-column>
          <el-table-column prop="titile" label="标题" width="200"></el-table-column>
          <el-table-column prop="content" label="内容"></el-table-column>
          <el-table-column prop="isRead" label="状态" width="100">
            <template slot-scope="scope">
              <span v-show="scope.row.isRead == 0">未读</span>
              <span v-show="scope.row.isRead == 1">已读</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="发送时间" width="200"></el-table-column>
          <el-table-column prop="status" label="操作" width="100">
            <template slot-scope="scope">
              <el-button v-show="scope.row.status == 0" size="mini" type="text" @click="delUserScriptLog(scope.row)">
                撤销
              </el-button>
              <el-button v-show="scope.row.status == 1" size="mini" type="text" disabled>已撤销</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <pagination
        v-show="userScriptLogQuery.total>0"
        :total="userScriptLogQuery.total"
        :page.sync="userScriptLogQuery.pageNum"
        :limit.sync="userScriptLogQuery.pageSize"
        @pagination="getUserScriptLogList"
      />
    </el-dialog>

    <!-- 查看用户积分列表   -->
    <el-dialog title="积分记录" :visible.sync="userIntegralLogVisible" width="90%"
               :before-close="cancelUserIntegralLogDialog">
      <template>
        <el-table :data="userIntegralLogQuery.userIntegralLogList" @sort-change="userIntegralSortChang"
                  :default-sort="{prop: 'createTime', order: 'desc'}" :stripe="true" style="width: 100%">
          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column prop="source" label="类型" width="100px">
            <template slot-scope="scope">
              <span v-show="scope.row.source == 1">增加积分</span>
              <span v-show="scope.row.source == 2">减少积分</span>
            </template>
          </el-table-column>
          <el-table-column prop="floatScore" label="变动积分"
                           :sortable="'custom'" width="100"></el-table-column>
          <el-table-column prop="soureId" label="来源ID" width="100"></el-table-column>
          <el-table-column prop="remarkContent" label="说明"></el-table-column>
          <el-table-column prop="createTime" :sortable="'custom'" label="操作时间" width="200"></el-table-column>
        </el-table>
      </template>
      <pagination
        v-show="userIntegralLogQuery.total>0"
        :total="userIntegralLogQuery.total"
        :page.sync="userIntegralLogQuery.pageNum"
        :limit.sync="userIntegralLogQuery.pageSize"
        @pagination="getUserIntegralLogList"
      />
    </el-dialog>

    <!-- 导出字段选择弹窗   -->
    <el-dialog title="自定义导出字段" :visible.sync="exportFieldsVisible" width="50%"
               :before-close="cancelExportFieldsDialog">
      <el-form ref="form" label-width="150px">
        <el-form-item label="全部字段" prop="allFields">
          <el-switch v-model="allFields" @click.native="isExportAllFields()"/>
        </el-form-item>
      </el-form>
      <el-form :inline="true" ref="form" :model="exportFieldList" label-width="150px">
        <el-form-item label="会员昵称" prop="nickname">
          <el-switch v-model="exportFieldList.nickname" :active-value="'nickname'" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="用户编号 " prop="id">
          <el-switch v-model="exportFieldList.id" active-value="id" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="手机号 " prop="mobile">
          <el-switch v-model="exportFieldList.mobile" active-value="mobile" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="生日 " prop="birthday">
          <el-switch v-model="exportFieldList.birthday" active-value="birthday" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="地区 " prop="province" @click.native="exportArea()">
          <el-switch v-model="exportFieldList.province" active-value="province" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="用户注册时间 " prop="createTime">
          <el-switch v-model="exportFieldList.createTime" active-value="createTime" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="仪器数量 " prop="devicesNum">
          <el-switch v-model="exportFieldList.devicesNum" active-value="devicesNum" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="仪器名称 " prop="devicesName">
          <el-switch v-model="exportFieldList.devicesName" active-value="devicesName" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="小程序标签 " prop="miniProgramTags">
          <el-switch v-model="exportFieldList.miniProgramTags" active-value="miniProgramTags" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="外部标签 " prop="wecomTags">
          <el-switch v-model="exportFieldList.wecomTags" active-value="wecomTags" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="积分 " prop="credit">
          <el-switch v-model="exportFieldList.credit" active-value="credit" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="即将过期积分 " prop="expireCredit">
          <el-switch v-model="exportFieldList.expireCredit" active-value="expireCredit" :inactive-value="null"/>
        </el-form-item>
        <el-form-item label="unionid " prop="unionid">
          <el-switch v-model="exportFieldList.unionid" active-value="unionid" :inactive-value="null"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelExportFieldsDialog()">取 消</el-button>
        <el-button type="primary" @click="submitBatchOperate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看用户绑定的仪器列表   -->
    <el-dialog title="仪器绑定" :visible.sync="userInstrumentVisible" width="63%" :before-close="cancelUserInstrumentDialog">
      <template>
        <el-table :data="userInstrumentQuery.userInstrumentList" style="width: 100%">
          <el-table-column type="index" width="50" label="序号" />
          <el-table-column prop="instrumentName" label="仪器名称" width="150px" />
          <el-table-column prop="serial" label="仪器序列号" width="200" />
          <el-table-column prop="serialImage" label="仪器序列号图片" width="150" >
            <template slot-scope="scope">
              <el-image v-if="scope.row.serialImage" :src="scope.row.serialImage"
                        style="width: 100px; height: 100px" ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="操作时间" width="200" />
        </el-table>
      </template>
      <pagination
        v-show="userInstrumentQuery.total>0"
        :total="userInstrumentQuery.total"
        :page.sync="userInstrumentQuery.pageNum"
        :limit.sync="userInstrumentQuery.pageSize"
        @pagination="getUserInstrumentList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  listMember,
  getMember,
  delMember,
  updateMember,
  selectUserCount,
  getMiniProgramTags,
  getWecomTags,
  getPurchaseChannel,
  getRegionByPid,
  batchAddMiniProgramTag,
  allAddMiniProgramTag,
  batchDelMiniProgramTag,
  allDelMiniProgramTag,
  batchChangIntegral,
  allChangIntegral,
  batchSendScript,
  allSendScript,
  batchAddRemark,
  allAddRemark,
  getMiniProgramTagsTree,
  scriptTreeSelect,
  editRemark,
  delRemark,
  openOrCloseClock,
  openOrCloseActivity,
  uObtainUserScriptLog,
  delUserScriptLog,
  obtainUserIntegralLog,
  getAllInstrument, listUserInstrument,
} from "@/api/system/member";
import Treeselect from "@riophae/vue-treeselect";
import {tagTreeSelect} from "@/api/system/wechatTab";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Member",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      memberList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 修改用户备注弹出层
      editRemarkVisible: false,
      editRemarkForm: {
        id: null,
        content: null
      },
      // 日期范围
      dateRange: [],
      // 表头统计
      count: {
        userNum: 0,
        userRegisterNum: 0,
        userDeviceNum: 0
      },
      // 查询条件：仪器列表
      deviceList: [],
      // 查询条件，小程序二级标签
      miniProgramTags: [],
      // 小程序标签树
      miniProgramTagTree: [],
      // 外部标签树
      wecomTagTree: [],
      // 查询条件，企微二级标签
      wecomTags: [],
      // 查询条件：购买渠道
      purchaseChannels: null,
      // 查询条件：省市区
      provinceList: null,
      cityList: null,
      areaList: null,
      // 保存页面的，市区
      saveCityList: null,
      saveAreaList: null,
      chatTagOptions: [],
      scriptOptions: [],
      tagIdArray: [],
      // 批量操作类型-下拉项选择
      batchOperateValue: null,
      // 批量操作：小程序标签
      batchMiniProgramVisible: false,
      miniProgramForm: {
        tagIdArray: []
      },
      // 批量操作：积分
      batchIntegralVisible: false,
      integralForm: {
        source: null,
        floatScore: null,
        remarkContent: "后台操作"
      },
      // 批量操作：备注
      batchScriptVisible: false,
      remarkForm: {
        content: null,
        userIdList: null,
      },
      // 批量操作：发送话术
      batchRemarkVisible: null,
      scriptForm: {
        userIdList: null,
        isCustom: 0,
        scriptTemplateId: null,
        scriptName: null,
        titile: null,
        content: null,
        tagType: null,
        type: null,
        link: null,
        linkParams: null,
        redirectAppid: null,
        redirectUrl: null,
        videoNo: null,
        feedId: null,
        // 当类型为模板发送时，选择了二级话术标题后，显示内容用，不传后端保存
        scriptContent: null,
        // 选中的小程序标签
        tagIds: [],
        tagNames: [],
      },
      // 用户消息记录
      userScriptLogVisible: false,
      userScriptLogQuery: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        wxUserId: null,
        userScriptList: null,
        orderByColumn: "createTime",
        isAsc: "desc"
      },
      // 用户积分记录
      userIntegralLogVisible: false,
      userIntegralLogQuery: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        userIntegralLogList: null,
        userId: null,
        orderByColumn: "createTime",
        isAsc: "desc"
      },
      // 用户仪器列表
      userInstrumentVisible: false,
      userInstrumentQuery: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userInstrumentList: null,
        orderByColumn: "createTime",
        isAsc: "desc"
      },
      // 导出数据选择字段
      exportFieldsVisible: false,
      exportFieldsForm: {
        userIdList: null,
        exportFields: null,
      },
      allFields: false,
      exportFieldList: {
        id: null,
        nickname: null,
        credit: null,
        expireCredit: null,
        unionid: null,
        mobile: null,
        province: null,
        city: null,
        area: null,
        birthday: null,
        devicesNum: null,
        devicesName: null,
        createTime: null,
        wecomTags: null,
        miniProgramTags: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickname: null,
        headimg: null,
        username: null,
        deviceNumStart: undefined,
        deviceNumEnd: undefined,
        creditStart: undefined,
        creditEnd: undefined,
        openid: null,
        unionid: null,
        userType: null,
        level: null,
        mobile: null,
        password: null,
        userQr: null,
        provinceId: null,
        province: null,
        cityId: null,
        city: null,
        areaId: null,
        area: null,
        birthday: null,
        clock: null,
        activity: null,
        wechat: null,
        code: null,
        isAbutment: null,
        collagenDay: null,
        collagenMount: null,
        loginTime: null,
        status: null,
        // createTime: [],
        devicesIdList: [],  //仪器绑定
        wecomTags: [], // 外部标签
        miniProgramTags: [], // 小程序标签
        purchaseChannels: [], // 购买渠道
        isCompleteInformation: null, // 用户信息是否完善
        wxUserRemarkList: null, // 备注列表
      },
      // 表单参数
      form: {},
      // 表单校验
      batchMiniProgramRules: {
        tagIdArray: [
          {required: true, message: '请选择小程序标签', trigger: 'change'}
        ],
      },
      batchIntegralRules: {
        source: [
          {required: true, message: '请选择积分操作类型', trigger: 'blur'}
        ],
        floatScore: [
          {required: true, message: '请输入变动积分', trigger: 'change'}
        ],
        remarkContent: [
          {required: true, message: '输入积分操作说明', trigger: 'blur'},
          {min: 1, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur'}
        ],
      },
      batchRemarkRules: {
        content: [
          {required: true, message: '请输入备注', trigger: 'blur'}
        ],
      },
      batchScriptRules: {
        isCustom: [
          {required: true, message: '请选择话术类型', trigger: 'change'}
        ],
        scriptTemplateId: [
          {required: true, message: '请选择话术标题', trigger: 'change'}
        ],
        // scriptContent: [
        //   {required: true, message: '请选择话术标题'}
        // ],
        titile: [
          {required: true, message: '请输入话术标题', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入话术内容', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请选择跳转类型', trigger: 'change'}
        ],
        link: [
          {required: true, message: '请输入链接地址', trigger: 'blur'}
        ],
        linkParams: [
          {required: true, message: '请输入跳转参数', trigger: 'blur'}
        ],
        redirectAppid: [
          {required: true, message: '请输入小程序APPID', trigger: 'blur'}
        ],
        redirectUrl: [
          {required: true, message: '请输入小程序页面', trigger: 'blur'}
        ],
        videoNo: [
          {required: true, message: '请输入视频号ID', trigger: 'blur'}
        ],
        feedId: [
          {required: true, message: '请输入视频号feedId', trigger: 'blur'}
        ],
      },
    };
  },
  created() {
    // 查询条件创建时间默认为当天
    // let siteStartTime = this.dateUtil(new Date(new Date().toLocaleDateString()));
    // let siteEndTime = this.dateUtil(new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1));
    // this.dateRange = [siteStartTime, siteEndTime];

    // 获取用户统计信息
    this.getUserCount();
    // 获取表单数据
    this.getList();
    // 获取标签
    this.getTags();
    // 获取省
    this.getProvinceList();
    // 获取标签树
    this.getDeptTree();
    this.getScriptTree();
    // 获取仪器列表
    this.getAllInstrument();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listMember(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.memberList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    dateUtil(date) {
      // 获取年份、月份和日期
      const year = date.getFullYear().toString(); // 四位数表示的年份
      const months = (date.getMonth() + 1).toString().padStart(2, '0'); // 补零后的两位数表示的月份
      const day = date.getDate().toString().padStart(2, '0'); // 补零后的两位数表示的日期
      const hours = date.getHours().toString().padStart(2, '0'); // 补全两位数的小时
      const minutes = date.getMinutes().toString().padStart(2, '0'); // 补全两位数的分钟
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${months}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 获取仪器列表
    getAllInstrument() {
      getAllInstrument().then(Response => {
        this.deviceList = Response.data;
        console.log(this.deviceList);
      })
    },
    getUserCount() {
      selectUserCount().then(Response => {
        this.count.userNum = Response.data[0];
        this.count.userRegisterNum = Response.data[1];
        this.count.userDeviceNum = Response.data[2];
      })
    },
    getTags() {
      // 小程序标签
      getMiniProgramTags().then(Response => {
        this.miniProgramTags = Response.data
      })
      // 微信标签
      getWecomTags().then(Response => {
        this.wecomTags = Response.data
      })
      // 购买渠道
      getPurchaseChannel().then(Response => {
        this.purchaseChannels = Response.data
      })
      // 小程序标签树
      getMiniProgramTagsTree().then(Response => {
        this.miniProgramTagTree = Response.data
      })
      // 外部标签树
      tagTreeSelect({type: 2}).then(response => {
        this.wecomTagTree = response.data;
      });
    },
    // 查询条件-获取省市区
    getProvinceList() {
      getRegionByPid(0).then(Response => {
        this.provinceList = Response.data
      })
    },
    getCityList(pid) {
      if (pid == '') {
        return;
      }
      this.queryParams.cityId = null;
      this.queryParams.areaId = null;
      getRegionByPid(pid).then(Response => {
        this.cityList = Response.data;
      })
    },
    getAreaByPid(pid) {
      if (pid == '') {
        return;
      }
      this.queryParams.areaId = null;
      getRegionByPid(pid).then(Response => {
        this.areaList = Response.data;
      })
    },
    // 查询条件-省市区清空
    clearOption(option) {
      // 省级清空
      if (option == 1) {
        this.queryParams.cityId = null;
        this.queryParams.areaId = null;
        this.cityList = null;
        this.areaList = null;
      }
      // 市级清空
      if (option == 2) {
        this.queryParams.areaId = null;
        this.areaList = null;
      }
    },
    // 修改-获取省市区
    getSaveCityList(pid) {
      if (pid == '') {
        return;
      }
      this.form.cityId = null;
      this.form.areaId = null;
      getRegionByPid(pid).then(Response => {
        this.saveCityList = Response.data;
      })
    },
    getSaveAreaByPid(pid) {
      if (pid == '') {
        return;
      }
      this.form.areaId = null;
      getRegionByPid(pid).then(Response => {
        this.saveAreaList = Response.data;
      })
    },
    clearSaveOption(option) {
      // 省级清空
      if (option == 1) {
        this.form.cityId = null;
        this.form.areaId = null;
        this.saveCityList = null;
        this.saveAreaList = null;
      }
      // 市级清空
      if (option == 2) {
        this.form.areaId = null;
        this.saveAreaList = null;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 关闭添加小程序标签窗口
    cancelMiniProgramDialog(isClose) {
      this.miniProgramForm.tagIdArray = [];
      if (isClose) {
        this.title = null;
        this.batchMiniProgramVisible = false;
      }
    },
    cancelIntegralDialog(isClose) {
      this.integralForm.source = null;
      this.integralForm.floatScore = null;
      this.integralForm.remarkContent = "后台操作";
      if (isClose) {
        this.batchIntegralVisible = false;
      }
    },
    cancelRemarkDialog(isClose) {
      this.remarkForm.content = null;
      if (isClose) {
        this.batchRemarkVisible = false;
      }
    },
    cancelUserScriptLogDialog() {
      this.userScriptLogVisible = false;
      this.userScriptLogQuery = {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        wxUserId: null,
        userScriptList: null,
        orderByColumn: "createTime",
        isAsc: "desc"
      }
    },
    cancelUserIntegralLogDialog() {
      this.userIntegralLogVisible = false;
      this.userIntegralLogQuery = {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        userIntegralLogList: null,
        userId: null,
        orderByColumn: "createTime",
        isAsc: "desc"
      }
    },
    cancelExportFieldsDialog() {
      this.allFields = false;
      this.exportFieldsVisible = false
      this.exportFieldList = {
        id: null,
        nickname: null,
        credit: null,
        expireCredit: null,
        unionid: null,
        mobile: null,
        province: null,
        city: null,
        area: null,
        birthday: null,
        devicesNum: null,
        devicesName: null,
        createTime: null,
        wecomTags: null,
        miniProgramTags: null,
      }
    },
    cancelScriptDialog(isClose) {
      this.scriptForm = {
        userIdList: null,
        isCustom: 0,
        scriptTemplateId: null,
        scriptName: null,
        titile: null,
        content: null,
        tagType: null,
        type: null,
        link: null,
        linkParams: null,
        redirectAppid: null,
        redirectUrl: null,
        videoNo: null,
        feedId: null,
        scriptContent: null,
        tagNames: [],
        tagIds: [],
      }
      if (isClose) {
        this.batchScriptVisible = false;
      }
    },
    cancelUserInstrumentDialog() {
      this.userInstrumentVisible = false;
      this.userInstrumentQuery = {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userInstrumentList: null,
        orderByColumn: "createTime",
        isAsc: "desc"
      }
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      tagTreeSelect({type: 1}).then(response => {
        this.chatTagOptions = response.data;
      });
    },
    /** 查询话术下拉树结构 */
    getScriptTree() {
      scriptTreeSelect().then(response => {
        this.scriptOptions = response.data;
      });
    },
    // 切换 话术发送类型
    clearScript() {
      if (this.scriptForm.isCustom == 0) {
        this.scriptForm.scriptName = null;
        this.scriptForm.titile = null;
        this.scriptForm.content = null;
        this.scriptForm.tagType = null;
        this.scriptForm.type = null;
        this.scriptForm.link = null;
        this.scriptForm.linkParams = null;
        this.scriptForm.redirectAppid = null;
        this.scriptForm.redirectUrl = null;
        this.scriptForm.videoNo = null;
        this.scriptForm.feedId = null;
        this.scriptForm.tagNames = null;
        this.scriptForm.tagIds = null;
      }
      // 自定义发送
      if (this.scriptForm.isCustom == 1) {
        this.scriptForm.scriptTemplateId = null;
        this.scriptForm.scriptContent = null;
        this.scriptForm.type = 0;
      }
    },
    selectTree(raw, instanceId) {
      this.scriptForm.scriptContent = raw.content;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        nickname: null,
        headimg: null,
        username: null,
        credit: null,
        openid: null,
        unionid: null,
        userType: null,
        level: null,
        mobile: null,
        password: null,
        userQr: null,
        province: null,
        provinceId: null,
        city: null,
        cityId: null,
        area: null,
        areaId: null,
        birthday: null,
        clock: null,
        activity: null,
        wechat: null,
        code: null,
        isAbutment: null,
        collagenDay: null,
        collagenMount: null,
        loginTime: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    // 表单重置
    resetQueryParams() {
      // 查询参数
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        nickname: null,
        headimg: null,
        username: null,
        deviceNumStart: undefined,
        deviceNumEnd: undefined,
        creditStart: undefined,
        creditEnd: undefined,
        openid: null,
        unionid: null,
        userType: null,
        level: null,
        mobile: null,
        password: null,
        userQr: null,
        provinceId: null,
        province: null,
        cityId: null,
        city: null,
        areaId: null,
        area: null,
        birthday: null,
        clock: null,
        activity: null,
        wechat: null,
        code: null,
        isAbutment: null,
        collagenDay: null,
        collagenMount: null,
        loginTime: null,
        status: null,
        // createTime: [],
        devicesName: [],  //仪器绑定
        wecomTags: [], // 外部标签
        miniProgramTags: [], // 小程序标签
        purchaseChannels: [], // 购买渠道
        isCompleteInformation: null, // 用户信息是否完善
        wxUserRemarkList: null, // 备注列表
      };
      this.resetForm("queryForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetQueryParams();
      this.handleQuery();
    },
    /** 批量操作按钮，显示批量操作弹窗 */
    batchOperate() {
      if (this.batchOperateValue == null) {
        this.$message({
          message: '请选择要批量操作类型',
          type: 'warning'
        })
        return
      } else {
        /* 批量操作 小程序标签 */
        if (this.batchOperateValue == 1 || this.batchOperateValue == 2) {
          if (this.ids.length == 0) {
            this.$message({
              message: '请选择要操作的数据',
              type: 'warning'
            })
            return
          }
          if (this.batchOperateValue == 1) {
            this.title = "添加小程序标签";
          }
          if (this.batchOperateValue == 2) {
            this.title = "删除小程序标签";
          }
          this.batchMiniProgramVisible = true;
        }
        if (this.batchOperateValue == 3 || this.batchOperateValue == 4) {
          if (this.batchOperateValue == 3) {
            this.title = "添加小程序标签";
          }
          if (this.batchOperateValue == 4) {
            this.title = "删除小程序标签";
          }
          this.batchMiniProgramVisible = true;
        }

        /* 批量操作：加减分 */
        if (this.batchOperateValue == 5) {
          if (this.ids.length == 0) {
            this.$message({
              message: '请选择要操作的数据',
              type: 'warning'
            })
            return
          }
          this.batchIntegralVisible = true;
          this.title = "批量加减积分";
        }
        if (this.batchOperateValue == 6) {
          this.batchIntegralVisible = true;
          this.title = "全量加减积分";
        }

        /* 批量操作：发送话术 */
        if (this.batchOperateValue == 7) {
          if (this.ids.length == 0) {
            this.$message({
              message: '请选择要操作的数据',
              type: 'warning'
            })
            return
          }
          this.batchScriptVisible = true;
          this.title = "批量发送话术";
        }
        if (this.batchOperateValue == 8) {
          this.batchScriptVisible = true;
          this.title = "全量发送话术";
        }

        /* 批量操作： 备注 */
        if (this.batchOperateValue == 9) {
          if (this.ids.length == 0) {
            this.$message({
              message: '请选择要操作的数据',
              type: 'warning'
            })
            return
          }
          this.batchRemarkVisible = true;
          this.title = "批量备注";
        }
        if (this.batchOperateValue == 10) {
          this.batchRemarkVisible = true;
          this.title = "全量备注";
        }

        /* 批量操作：注销账号 */
        if (this.batchOperateValue == 11) {
          if (this.ids.length == 0) {
            this.$message({
              message: '请选择要操作的数据',
              type: 'warning'
            })
            return
          }
          this.$confirm("<span style='font-size: 18px'><strong>确定将选择的数据注销?</strong></span><br/><span style='padding-left:2em'>请谨慎操作，一旦成功将无法撤销。</span>", '注销账号', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          }).then(() => {
            delMember(this.ids).then(Response => {
              this.$modal.msgSuccess("批量删除会员成功");
              this.cancelIntegralDialog(true);
            })
          }).catch(() => {
          });
        }

        /* 批量操作：导出数据 */
        if (this.batchOperateValue == 12) {
          if (this.ids.length == 0) {
            this.$message({
              message: '请选择要操作的数据',
              type: 'warning'
            })
            return
          }
          this.exportFieldsVisible = true;
        }
        if (this.batchOperateValue == 13) {
          this.exportFieldsVisible = true;
        }
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMember(id).then(response => {
        // 回显省市区
        if (response.data.provinceId != null) {
          this.getSaveCityList(response.data.provinceId);
        }
        if (response.data.areaId != null) {
          this.getSaveAreaByPid(response.data.cityId);
        }

        this.form = response.data;
        this.open = true;
        this.title = "修改用户";
      });
    },
    // 开关打卡
    openOrCloseClock(row) {
      let spanContent;
      let title;
      if (row.clock == 1) {
        spanContent = "确定将选择的数据禁止打卡？";
        title = "禁止打卡";
      } else {
        spanContent = "确定将选择的数据开启打卡？";
        title = "开启打卡";
      }
      this.$confirm("<span style='font-size: 18px'><strong>" + spanContent + "</strong></span><br/><span style='padding-left:2em'>请谨慎操作，一旦成功将无法撤销。</span>", title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        openOrCloseClock(row.id).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        });
      }).catch(() => {
      });
    },
    // 开关活动
    openOrCloseActivity(row) {
      let spanContent;
      let title;
      if (row.activity == 1) {
        spanContent = "确定将选择的数据禁止活动？";
        title = "禁止活动";
      } else {
        spanContent = "确定将选择的数据开启活动？";
        title = "开启活动";
      }
      this.$confirm("<span style='font-size: 18px'><strong>" + spanContent + "</strong></span><br/><span style='padding-left:2em'>请谨慎操作，一旦成功将无法撤销。</span>", title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        openOrCloseActivity(row.id).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        });
      }).catch(() => {
      });
    },
    // 信息同步
    informationSynchronization(row) {
      this.$confirm("<span style='font-size: 18px'><strong>确定将选择的数据信息同步？</strong></span><br/><span style='padding-left:2em'>请谨慎操作，一旦成功将无法撤销。</span>", "信息同步", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        alert("用户id" + row.id);
      }).catch(() => {
      });
    },
    // 积分同步
    integralSynchronization(row) {
      this.$confirm("<span style='font-size: 18px'><strong>确定将选择的数据积分同步？</strong></span><br/><span style='padding-left:2em'>请谨慎操作，一旦成功将无法撤销。</span>", "积分同步", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        alert("用户id" + row.id);
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.id != null) {
        updateMember(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        this.$modal.msgError("修改失败");
      }
    },
    /* 批量操作提交按钮 */
    submitBatchOperate() {
      // 批量添加小程序标签
      if (this.batchOperateValue == 1) {
        this.$refs["miniProgramForm"].validate(valid => {
          if (valid) {
            batchAddMiniProgramTag(this.miniProgramForm.tagIdArray, this.ids).then(Response => {
              this.$modal.msgSuccess("批量添加小程序标签成功");
              this.cancelMiniProgramDialog(true);
            })
          }
        });
      }
      // 批量删除小程序标签
      if (this.batchOperateValue == 2) {
        this.$refs["miniProgramForm"].validate(valid => {
          if (valid) {
            batchDelMiniProgramTag(this.miniProgramForm.tagIdArray, this.ids).then(Response => {
              this.$modal.msgSuccess("批量删除小程序标签成功");
              this.cancelMiniProgramDialog(true);
            })
          }
        });
      }
      // 全量添加小程序标签
      if (this.batchOperateValue == 3) {
        this.$refs["miniProgramForm"].validate(valid => {
          if (valid) {
            allAddMiniProgramTag(this.miniProgramForm.tagIdArray, this.queryParams).then(Response => {
              this.$modal.msgSuccess("全量添加小程序标签成功");
              this.cancelMiniProgramDialog(true);
            })
          }
        });
      }
      // 全量删除小程序标签
      if (this.batchOperateValue == 4) {
        this.$refs["miniProgramForm"].validate(valid => {
          if (valid) {
            allDelMiniProgramTag(this.miniProgramForm.tagIdArray, this.queryParams).then(Response => {
              this.$modal.msgSuccess("全量删除小程序标签成功");
              this.cancelMiniProgramDialog(true);
            })
          }
        });
      }

      // 批量操作积分
      if (this.batchOperateValue == 5) {
        this.$refs["integralForm"].validate(valid => {
          if (valid) {
            batchChangIntegral(this.ids, this.integralForm).then(Response => {
              this.$modal.msgSuccess("批量操作积分成功");
              this.cancelIntegralDialog(true);
            })
          }
        })
      }
      // 全量操作积分
      if (this.batchOperateValue == 6) {
        this.$refs["integralForm"].validate(valid => {
          if (valid) {
            allChangIntegral(this.integralForm, this.queryParams).then(Response => {
              this.$modal.msgSuccess("批量操作积分成功");
              this.cancelIntegralDialog(true);
            })
          }
        })
      }

      /* 批量操作：发送话术 */
      if (this.batchOperateValue == 7) {
        this.scriptForm.userIdList = this.ids;
        batchSendScript(this.scriptForm).then(Response => {
          this.$modal.msgSuccess("批量发送话术成功");
          this.cancelScriptDialog(true);
        })
      }
      if (this.batchOperateValue == 8) {
        allSendScript(this.scriptForm, this.queryParams).then(Response => {
          this.$modal.msgSuccess("全量发送话术成功");
          this.cancelScriptDialog(true);
        })
      }

      // 批量操作备注
      if (this.batchOperateValue == 9) {
        this.$refs["remarkForm"].validate(valid => {
          if (valid) {
            this.remarkForm.userIdList = this.ids;
            batchAddRemark(this.remarkForm).then(Response => {
              this.$modal.msgSuccess("批量备注成功");
              this.cancelRemarkDialog(true);
            })
          }
        })
      }
      // 全量操作备注
      if (this.batchOperateValue == 10) {
        this.$refs["remarkForm"].validate(valid => {
          if (valid) {
            allAddRemark(this.remarkForm.content, this.queryParams).then(Response => {
              this.$modal.msgSuccess("批量备注成功");
              this.cancelRemarkDialog(true);
            })
          }
        })
      }

      // 导出用户数据
      if (this.batchOperateValue == 12) {
        let exportFields = Object.values(this.exportFieldList).filter(val => val != null);
        if (exportFields.length == 0) {
          this.$modal.msgError("请选择导出字段");
          return;
        }
        this.exportFieldsForm.userIdList = this.ids;
        this.exportFieldsForm.exportFields = exportFields;
        this.download('/system/member/batchExport', {
          ...this.exportFieldsForm
        }, `微信会员_${new Date().getTime()}.xlsx`);
        this.cancelExportFieldsDialog();
      }
      if (this.batchOperateValue == 13) {
        let exportFields = Object.values(this.exportFieldList).filter(val => val != null);
        if (exportFields.length == 0) {
          this.$modal.msgError("请选择导出字段");
          return;
        }
        this.download('/system/member/allExport', {
          ...Object.assign({}, this.queryParams, {exportFields: exportFields})
        }, `微信会员_${new Date().getTime()}.xlsx`)
        this.cancelExportFieldsDialog();
      }
    },
    // 打开用户备注修改
    ocEditRemarkDialog(row) {
      this.editRemarkVisible = !this.editRemarkVisible;
      if (this.editRemarkVisible) {
        this.editRemarkForm.id = row.id;
        this.editRemarkForm.content = row.content;
      } else {
        this.editRemarkForm.content = null;
        this.editRemarkForm.id = null;
      }
    },
    // 保存用户备注
    submitEditRemark() {
      editRemark(this.editRemarkForm).then(Response => {
        this.$modal.msgSuccess("修改备注成功");
        if (this.form.wxUserRemarkList != null && this.form.wxUserRemarkList.length > 0) {
          let that = this;
          this.form.wxUserRemarkList.forEach(function (item) {
            if (item.id == that.editRemarkForm.id) {
              item.content = that.editRemarkForm.content;
            }
          })
        }
        this.ocEditRemarkDialog();
      })
    },
    // 删除用户备注
    submitDelRemark(row) {
      this.$confirm("<span style='font-size: 18px'><strong>确定将选择的备注删除吗?</strong></span><br/>", '删除备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        delRemark(row.id).then(Response => {
          this.$modal.msgSuccess("删除用户备注成功");
          let list = this.form.wxUserRemarkList;
          for (let i = 0; i < list.length; i++) {
            if (list[i].id == row.id) {
              this.form.wxUserRemarkList.splice(i, 1);
            }
          }
        })
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + ids + '"的数据项？').then(function () {
        return delMember(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 打开用户消息列表窗口
    viewMessageDetail(row) {
      this.userScriptLogQuery.wxUserId = row.id;
      this.getUserScriptLogList();
      this.userScriptLogVisible = true;
    },
    // 分页获取 用户消息列表
    getUserScriptLogList() {
      uObtainUserScriptLog(this.userScriptLogQuery).then(response => {
        this.userScriptLogQuery.userScriptList = response.rows;
        this.userScriptLogQuery.total = response.total;
      });
    },
    // 打开用户仪器列表窗口
    viewUserInstrumentDetail(row) {
      this.userInstrumentQuery.userId = row.id;
      this.getUserInstrumentList();
      this.userInstrumentVisible = true;
    },
    // 分页获取 用户消息列表
    getUserInstrumentList() {
      listUserInstrument(this.userInstrumentQuery).then(response => {
        this.userInstrumentQuery.userInstrumentList = response.rows;
        this.userInstrumentQuery.total = response.total;
      });
    },
    // 删除用户消息
    delUserScriptLog(row) {
      let wxUserScriptLog = {
        id: row.id,
        status: row.status == 0 ? 1 : 0,
      }
      delUserScriptLog(wxUserScriptLog).then(Response => {
        row.status = wxUserScriptLog.status;
        this.$modal.msgSuccess("撤销成功");
      })
    },
    // 打开用户积分列表窗口
    viewUserIntegralDetail(row) {
      this.userIntegralLogQuery.userId = row.id;
      this.getUserIntegralLogList();
      this.userIntegralLogVisible = true;
    },
    // 分页获取用户积分列表
    getUserIntegralLogList() {
      obtainUserIntegralLog(this.userIntegralLogQuery).then(Response => {
        this.userIntegralLogQuery.userIntegralLogList = Response.rows;
        this.userIntegralLogQuery.total = Response.total;
      })
    },
    userIntegralSortChang({column, prop}) {
      this.userIntegralLogQuery.orderByColumn = prop;
      this.userIntegralLogQuery.isAsc = column.order == 'ascending' ? 'asc' : 'desc';
      this.getUserIntegralLogList();
    },
    isExportAllFields() {
      if (this.allFields) {
        this.exportFieldList.nickname = "nickname";
        this.exportFieldList.id = "id";
        this.exportFieldList.credit = "credit";
        this.exportFieldList.expireCredit = "expireCredit";
        this.exportFieldList.unionid = "unionid";
        this.exportFieldList.mobile = "mobile";
        this.exportFieldList.province = "province";
        this.exportFieldList.city = "city";
        this.exportFieldList.area = "area";
        this.exportFieldList.birthday = "birthday";
        this.exportFieldList.devicesNum = "devicesNum";
        this.exportFieldList.devicesName = "devicesName";
        this.exportFieldList.createTime = "createTime";
        this.exportFieldList.wecomTags = "wecomTags";
        this.exportFieldList.miniProgramTags = "miniProgramTags";
      } else {
        this.exportFieldList.nickname = null;
        this.exportFieldList.id = null;
        this.exportFieldList.credit = null;
        this.exportFieldList.expireCredit = null;
        this.exportFieldList.unionid = null;
        this.exportFieldList.mobile = null;
        this.exportFieldList.province = null;
        this.exportFieldList.city = null;
        this.exportFieldList.area = null;
        this.exportFieldList.birthday = null;
        this.exportFieldList.devicesNum = null;
        this.exportFieldList.devicesName = null;
        this.exportFieldList.createTime = null;
        this.exportFieldList.wecomTags = null;
        this.exportFieldList.miniProgramTags = null;
      }
    },
    exportArea() {
      if (this.exportFieldList.province != null) {
        this.exportFieldList.city = "city";
        this.exportFieldList.area = "area";
      } else {
        this.exportFieldList.city = null;
        this.exportFieldList.area = null;
      }
    }
  },
}
;
</script>
