<template>
  <div id="rtp_list" class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <el-select v-model="searchParams.model" placeholder="请选择生成比例">
      <el-option value="" label="全部" />
      <el-option
        v-for="(item, i) in codeModelList"
        :key="i"
        :label="item"
        :value="item"
      />
    </el-select>
    <!-- <el-date-picker
      v-model="searchParams.date"
      type="date"
      placeholder="选择日期时间"
      value-format="yyyy-MM-dd"
    /> -->
    <el-button
      type="primary"
      @click="
        rtpSearch
      "
    >搜索</el-button>
    <el-button type="primary" @click="codeVis.many = true">一键生成</el-button>
    <el-button type="primary" @click="searchCodeVis = true">查询防伪码</el-button>
    <!-- <el-button type="primary" @click="submitCreateOne(0)">单独生成</el-button> -->
    <!-- <el-button type="primary" @click="submitCodeExport">导出</el-button> -->
    <el-button type="primary" @click="teamSetVis = true">设置代理防伪码</el-button>
    <el-button type="primary" @click="showSelectCode">批量修改防伪码</el-button>
    <el-dialog
      title="批量设置子码真假"
      :visible.sync="childCodeVis"
      width="520px"
      :before-close="resetChildCode"
    >
      <el-form label-width="100px">
        <el-form-item label="子码真假:">
          <el-radio v-model="childCodeIsTrue" label="0">真</el-radio>
          <el-radio v-model="childCodeIsTrue" label="1">假</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitChildCodeSet">确定</el-button>
          <el-button @click="resetChildCode">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="批量修改防伪码"
      :visible.sync="selectCodeVis"
      width="520px"
    >
      <el-form label-width="100px">
        <el-form-item label="防伪码真假:">
          <el-radio v-model="selectCodeIsTrue" label="0">真</el-radio>
          <el-radio v-model="selectCodeIsTrue" label="1">假</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitSelectCodeSet">确定</el-button>
          <el-button @click="selectCodeVis = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="设置代理防伪码"
      :visible.sync="teamSetVis"
      :before-close="resetTeamSet"
      width="520px"
    >
      <el-form ref="teamSetForm" :model="teamSet" :rules="teamSetRules" label-width="100px">
        <el-form-item label="代理手机号:">
          <el-input v-model="teamSet.phone" type="text" />
        </el-form-item>
        <el-form-item label="防伪码真假:">
          <el-radio v-model="teamSet.is_true" label="0">真</el-radio>
          <el-radio v-model="teamSet.is_true" label="1">假</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitTeamSet">确认</el-button>
          <el-button @click="resetTeamSet">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-table
      :data="codeList"
      :header-cell-style="{ background: '#f8fbfc' }"
      border
      stripe
      style="margin-top: 20px"
      :row-key="getRowKeys"
      :expand-row-keys="expands"
      @expand-change="getCodeTrace"
    >
      <el-table-column type="expand">
        <template slot-scope="{ row:p_row }">
          <el-table
            ref="childTable"
            :data="p_row.codeTree"
            :header-cell-style="{ background: '#f8fbfc' }"
            border
            lazy
            stripe
            :load="getChildCode"
            row-key="id"
            :tree-props="{ children: 'get_child', hasChildren: 'hasChildren' }"
            style="margin-top: 20px"
            @selection-change="getCodeSelect"
          >
            <el-table-column
              type="selection"
              :selectable="(row, index) => row.is_lowest"
              width="55"
              align="center"
            />
            <el-table-column
              prop="security_code"
              label="防伪码"
              align="center"
            />
            <el-table-column
              prop="level"
              label="防伪码等级"
              align="center"
              width="100"
            />
            <el-table-column
              prop="code"
              label="长链接"
              align="center"
              width="300"
            />
            <el-table-column label="绑定代理" align="center">
              <template slot-scope="{ row: { user } }">
                <el-button
                  v-if="user"
                  type="text"
                  @click="handleSeeMemberInfo(user)"
                >{{ user.nickname }}</el-button>
                <span v-else>暂未绑定代理</span>
              </template>
            </el-table-column>
            <el-table-column label="公司绑定" align="center">
              <template slot-scope="{ row }">
                <el-tag :type="row.com_binding === 1 ? 'danger' : 'success'">{{
                  row.com_binding === 1 ? "未绑定" : "已绑定"
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="防伪码真假" align="center">
              <template slot-scope="{ row }">
                <template v-if="row.is_lowest === 0">
                  <el-tag type="info">未标示</el-tag>
                </template>
                <template v-else>
                  <el-tag :type="row.is_true === 1 ? 'danger' : 'success'">{{
                    row.is_true === 1 ? "假" : "真"
                  }}</el-tag>
                </template>
              </template>
            </el-table-column>
            <!-- <el-table-column label="是否发货" align="center">
              <template slot-scope="{ row }">
                <el-tag
                  :type="
                    row.track_status === 0
                      ? 'info'
                      : row.track_status === 1
                      ? 'warning'
                      : 'success'
                  "
                  >{{
                    row.track_status === 0
                      ? "未发货"
                      : row.track_status === 1
                      ? "部分发货"
                      : "全部发货"
                  }}</el-tag
                >
              </template>
            </el-table-column> -->
            <el-table-column
              label="商品信息"
              align="center"
            >
              <template slot-scope="{ row: { get_goods } }">
                <p v-if="!get_goods">暂未绑定商品</p>
                <p v-else>
                  {{ get_goods.good_name }}({{ get_goods.size }})({{ get_goods.sex === 1 ? '女款' : '男款' }})
                </p>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="{ row }">
                <ul class="tree_node_icons">
                  <li
                    class="tree_node_icon"
                    :class="row.get_express.length > 0 ? 'tree_node_icon_active' : ''"
                    @click="seeGoodExpress(row)"
                  >
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="查看发货信息"
                      placement="top"
                    >
                      <i class="el-icon-view" />
                    </el-tooltip>
                  </li>
                  <li class="tree_node_icon" @click="submitCodeTrue(row, p_row)">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="row.is_lowest === 0 ? '批量设置子码真假' : row.is_true === 1 ? '设置为真码' : '设置为假码'"
                      placement="top"
                    >
                      <i
                        :class="
                          row.is_true === 1 ? 'el-icon-check' : 'el-icon-close'
                        "
                      />
                    </el-tooltip>
                  </li>
                  <li class="tree_node_icon" @click="submitDeleteCode(row, p_row)">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="删除"
                      placement="top"
                    >
                      <i class="el-icon-delete" />
                    </el-tooltip>
                  </li>
                </ul>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            :total="p_row.codeTotal"
            :limit="traceInfo.page_size"
            :page="traceInfo.page_index"
            @pagination="data => changeTracePagination(data, p_row)"
            @update:limit="data => changeTracePagination(data, p_row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="批次" align="center">
        <template slot-scope="{ row }"> 第 {{ row.sort }} 批 </template>
      </el-table-column>
      <el-table-column prop="model" label="类型" align="center" />
      <el-table-column prop="num" label="生成数量(组)" align="center" />
      <el-table-column
        prop="created_at"
        label="生成时间"
        align="center"
      />
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <el-tag :type="row.status === 0 ? 'info' : 'success'">{{
            row.status === 0 ? "正在生成" : "已生成"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button type="text" @click="submitCodeExport(row.id)">导出</el-button>
          <el-button type="text" @click="submitDeleteTrace(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="codeListTotal"
      :limit="searchParams.page_size"
      :page="searchParams.page_index"
      @pagination="changePagination"
      @update:limit="changePagination"
    />
    <el-dialog
      title="一键生成"
      :visible.sync="codeVis.many"
      width="350px"
      :before-close="resetCreateMany"
    >
      <el-form
        ref="codeManyForm"
        label-width="100px;"
        :model="codeMany"
        :rules="codeManyRules"
      >
        <el-form-item label="生成数量:" prop="total">
          <el-input-number
            v-model="codeMany.total"
            :min="1"
            :max="3000"
            label="生成个数"
          />
        </el-form-item>
        <!-- <el-form-item label="生成级数:" prop="grade">
          <el-input-number v-model="codeMany.grade" :min="1" label="生成级数" />
        </el-form-item>
        <el-form-item label="每级数量:" prop="num">
          <el-input-number v-model="codeMany.num" :min="1" label="每级数量" />
        </el-form-item>-->
        <el-form-item label="生成比例:" prop="model">
          <el-select v-model="codeMany.model" placeholder="请选择">
            <el-option
              v-for="(item, i) in codeModelList"
              :key="i"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitCreateMany">生成</el-button>
          <el-button @click="resetCreateMany">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看代理详情 -->
    <el-drawer
      :title="`${memberInfo.realname} - ${levelStatus(memberInfo.level).name}`"
      :visible.sync="memberInfoVis"
      direction="rtl"
      size="35%"
    >
      <MemberInfo :info="memberInfo" :team-type="false" />
    </el-drawer>
    <el-drawer
      title="发货信息"
      :visible.sync="expressVis"
      direction="rtl"
      size="35%"
    >
      <el-form
        v-for="(item, i) in expressInfo"
        :key="i"
        label-width="120px"
        style="border-bottom: 1px solid #ccc"
      >
        <el-form-item label="发货人姓名:">
          {{ item.op_name }}
        </el-form-item>
        <el-form-item label="发货人手机号:">
          {{ item.op_phone }}
        </el-form-item>
        <el-form-item label="收货人姓名:">
          {{ item.accept_name }}
        </el-form-item>
        <el-form-item label="收货人手机号:">
          {{ item.accept_phone }}
        </el-form-item>
        <el-form-item label="发货时间:">
          {{ item.created_at }}
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 搜索 -->
    <el-dialog
      title="查询防伪码"
      :visible.sync="searchCodeVis"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="80%"
    >
      <el-input
        v-model="searchPhone"
        type="text"
        placeholder="手机号"
        style="width: 250px"
      />
      <el-input
        v-model="searchCode"
        type="text"
        placeholder="长链接"
        style="width: 500px"
      />
      <el-upload
        style="display: inline-block;"
        action=""
        :show-file-list="false"
        :http-request="uploadQrocdeDecode"
        accept=".jpeg, .jpg, .png"
      >
        <el-button type="primary">识别二维码</el-button>
      </el-upload>
      <el-button type="primary" @click="getSearchCode">查询</el-button>
      <el-button type="primary" @click="showSelectCode">批量修改防伪码</el-button>
      <el-table
        ref="childTable2"
        v-loading="codeLoading"
        :data="searchCodeList"
        :header-cell-style="{ background: '#f8fbfc' }"
        border
        lazy
        stripe
        :load="getChildCode"
        row-key="id"
        :tree-props="{ children: 'get_child', hasChildren: 'hasChildren' }"
        style="margin-top: 20px"
        @selection-change="getCodeSelect"
      >
        <el-table-column
          type="selection"
          :selectable="(row, index) => row.is_lowest"
          width="55"
          align="center"
        />
        <el-table-column
          prop="security_code"
          label="防伪码"
          align="center"
          width="200"
        />
        <el-table-column
          prop="level"
          label="防伪码等级"
          align="center"
          width="100"
        />
        <el-table-column
          prop="code"
          label="长链接"
          align="center"
          width="300"
        />
        <el-table-column
          prop="serial"
          label="所属批次"
          align="center"
        >
          <template slot-scope="{ row }">
            第 {{ row.serial }} 批
          </template>
        </el-table-column>
        <el-table-column
          prop="model"
          label="类型"
          align="center"
        />
        <el-table-column label="绑定代理" align="center">
          <template slot-scope="{ row: { user } }">
            <el-button
              v-if="user"
              type="text"
              @click="handleSeeMemberInfo(user)"
            >{{ user.nickname }}</el-button>
            <span v-else>暂未绑定代理</span>
          </template>
        </el-table-column>
        <el-table-column label="公司绑定" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="row.com_binding === 1 ? 'danger' : 'success'">{{
              row.com_binding === 1 ? "未绑定" : "已绑定"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="防伪码真假" align="center">
          <template slot-scope="{ row }">
            <template v-if="row.is_lowest === 0">
              <el-tag type="info">未标示</el-tag>
            </template>
            <template v-else>
              <el-tag :type="row.is_true === 1 ? 'danger' : 'success'">{{
                row.is_true === 1 ? "假" : "真"
              }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="商品信息"
          align="center"
        >
          <template slot-scope="{ row: { get_goods } }">
            <p v-if="!get_goods">暂未绑定商品</p>
            <p v-else>
              {{ get_goods.good_name }}({{ get_goods.size }})({{ get_goods.sex === 1 ? '女款' : '男款' }})
            </p>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="{ row }">
            <ul class="tree_node_icons">
              <li
                class="tree_node_icon"
                :class="row.get_express.length > 0 ? 'tree_node_icon_active' : ''"
                @click="seeGoodExpress(row)"
              >
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="查看发货信息"
                  placement="top"
                >
                  <i class="el-icon-view" />
                </el-tooltip>
              </li>
              <li class="tree_node_icon" @click="submitCodeTrue(row, null)">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="row.is_lowest === 0 ? '批量设置子码真假' : row.is_true === 1 ? '设置为真码' : '设置为假码'"
                  placement="top"
                >
                  <i
                    :class="
                      row.is_true === 1 ? 'el-icon-check' : 'el-icon-close'
                    "
                  />
                </el-tooltip>
              </li>
              <li class="tree_node_icon" @click="submitDeleteCode(row, null)">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top"
                >
                  <i class="el-icon-delete" />
                </el-tooltip>
              </li>
            </ul>
          </template>
        </el-table-column>
      </el-table>
      <div class="no_float">
        <pagination
          :total="searchCodeListTotal"
          :limit="searchParams.page_size"
          :page="searchParams.page_index"
          @pagination="searchChangePagination"
          @update:limit="searchChangePagination"
        />
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 解析二维码
import Qrcode from 'qrcode-decoder'
import * as apis from '@/api/rtp/index'
import MemberInfo from '../team/components/MemberInfo'
// 公共方法
import { levelStatus } from '@/filters/common'
export default {
  components: {
    MemberInfo
  },
  data() {
    const validateNum = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请填写信息'))
      } else {
        if (/^\d+$/.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正整数数字'))
        }
      }
    }
    return {
      codeLoading: false,
      searchCodeVis: false,
      defaultProps: {
        label: 'code',
        children: 'get_child'
      },
      searchParams: {
        search_name: '',
        page_index: 1,
        page_size: 20,
        model: '',
        date: new Date()
      },
      codeTree: [],
      codeTotal: 0,
      loadingFull: false,
      codeVis: {
        many: false
      },
      codeMany: {
        total: 1,
        // grade: 1,
        // num: 1,
        model: ''
      },
      codeManyRules: {
        total: [{ required: true, validator: validateNum, trigger: 'blur' }],
        // grade: [
        //   { required: true, validator: validateNum, trigger: 'blur' }
        // ],
        // num: [
        //   { required: true, validator: validateNum, trigger: 'blur' }
        // ],
        model: [
          { required: true, message: '请选择生成比例', trigger: 'change' }
        ]
      },
      memberInfo: {},
      memberInfoVis: false,
      codeModelList: [],
      codeList: [],
      codeListTotal: 0,
      traceInfo: {
        page_index: 1,
        page_size: 10,
        model: '',
        sort: ''
      },
      expands: [],
      expressVis: false,
      expressInfo: [],
      maps: new Map(),
      expendMaps: new Map(),
      searchCode: '',
      searchPhone: '',
      searchCodeList: [],
      teamSetVis: false,
      teamSet: {
        phone: '',
        is_true: ''
      },
      teamSetRules: {
        phone: [
          { required: true, message: '请输入要设置的代理手机号', trigger: 'blur' }
        ],
        is_true: [
          { required: true, message: '请选择防伪码真假', trigger: 'change' }
        ]
      },
      reviseSelectIds: [],
      selectCodeIsTrue: '',
      selectCodeVis: false,
      childCodeVis: false,
      childCodeIsTrue: '',
      childCodeParent: new Map(),
      searchCodeListTotal: 0,
      searchPageIndex: 1,
      searchPageSize: 20,
      selectPid: []
    }
  },
  watch: {
    searchCodeVis(a) {
      if (!a) {
        this.searchCode = ''
        this.searchPhone = ''
        this.searchCodeList = []
      }
    },
    'searchParams.model'(a) {
      this.rtpSearch()
    },
    'selectCodeVis'(a) {
      if (!a) {
        this.selectCodeIsTrue = ''
      }
    }
  },
  created() {
    this.levelStatus = levelStatus
    this.getCreateCodeModel()
  },
  methods: {
    submitSelectCodeSet() {
      if (this.reviseSelectIds.length === 0) {
        this.$message.error('请先选择要设置的防伪码')
        return false
      }
      if (!this.selectCodeIsTrue) {
        this.$message.error('请设置防伪码真假')
        return false
      }
      const loading = this.$loading()
      apis.selectCodeSet({
        ids: this.reviseSelectIds,
        is_true: this.selectCodeIsTrue
      }).then(res => {
        loading.close()
        if (res.code === 200) {
          this.$message.success('批量设置成功')
          this.selectCodeVis = false
          try {
            this.selectPid.map(p_id => {
              const { tree, treeNode, resolve } = this.maps.get(p_id) // 根据p_id取出对应的节点数据
              this.$set(this.$refs.childTable.store.states.lazyTreeNodeMap, p_id, [])
              this.getChildCode(tree, treeNode, resolve)
            })
          } catch (e) {
            console.log(e)
          }
        } else {
          this.$message.error(res.message || '批量设置防伪码失败')
        }
      }).catch(() => {
        loading.close()
        this.$message.error('批量设置防伪码失败')
      })
    },
    showSelectCode() {
      if (this.reviseSelectIds.length === 0) {
        this.$message.error('请先选择要设置的防伪码')
        return false
      }
      this.selectCodeVis = true
    },
    // 多选框
    getCodeSelect(row) {
      this.reviseSelectIds = row.map(({ id }) => id)
      const p_ids = row.map(({ p_id }) => p_id)
      this.selectPid = [...new Set(p_ids)]
    },
    resetTeamSet() {
      this.teamSet.phone = ''
      this.teamSet.is_true = ''
      this.teamSetVis = false
    },
    // 修改代理防伪码真假
    submitTeamSet() {
      this.$refs.teamSetForm.validate((valid) => {
        if (valid) {
          const loading = this.$loading()
          apis.teamSet(this.teamSet).then(res => {
            loading.close()
            if (res.code === 200) {
              this.$message.success('设置代理防伪码成功')
              this.resetTeamSet()
            } else {
              this.$message.error(res.message || '设置代理防伪码失败')
            }
          }).catch(() => {
            loading.close()
            this.$message.error('设置代理防伪码失败')
          })
        } else {
          return false
        }
      })
    },
    uploadQrocdeDecode({ file }) {
      const url = window.URL.createObjectURL(file)
      const qrcode = new Qrcode()
      qrcode.decodeFromImage(url).then(({ data }) => {
        if (data) {
          this.searchCode = data
        } else {
          this.$message.error('该图片未解析出任何内容')
        }
      })
    },
    rtpSearch() {
      this.searchParams.page_index = 1
      this.codeList = []
      this.codeListTotal = 0
      this.expendMaps.clear()
      this.resetTraceList()
      this.expands = []
      this.getRtpList()
    },
    getSearchCode() {
      this.searchCodeList = []
      this.codeLoading = true
      apis.searchCode({
        code: this.searchCode,
        phone: this.searchPhone,
        page_index: this.searchPageIndex,
        page_size: this.searchPageSize
      }).then(res => {
        this.codeLoading = false
        if (res.code === 200) {
          res.data.list.forEach(item => {
            item.hasChildren = item.child_num > 0
          })
          this.searchCodeList = res.data.list
          this.searchCodeListTotal = res.data.total
        } else {
          this.$message.error(res.message || '查询失败')
        }
      }).catch((e) => {
        this.codeLoading = false
        this.$message.error('查询失败')
      })
    },
    seeGoodExpress(data) {
      const { get_express } = data
      if (get_express.length === 0) {
        this.$message.error('商品暂无发货信息')
        return false
      }
      this.expressInfo = get_express.sort((a, b) => new Date(a.created_at).getTime() < new Date(b.created_at).getTime())
      this.expressVis = true
    },
    getRowKeys(row) {
      return row.id
    },
    async changeTracePagination(data, row) {
      const { page, limit } = data
      this.traceInfo.page_size = limit
      this.traceInfo.page_index = page
      await this.getTraceList((a, t) => {
        row.codeTree = a
        row.codeTotal = t
      })
    },
    async getCodeTrace(row, ex) {
      const { id: p_id } = row
      if (ex.length > 0) {
        this.expendMaps.set(p_id, { row, ex })
        this.resetTraceList()
        this.expands = []
        this.expands.push(row.id)
        const { model, sort } = row
        this.traceInfo.model = model
        this.traceInfo.sort = sort
        await this.getTraceList((a, t) => {
          row.codeTree = a
          row.codeTotal = t
        })
      } else {
        this.expendMaps.delete(p_id)
        this.resetTraceList()
        row.codeTree = []
        row.codeTotal = 0
        this.expands = []
      }
    },
    resetTraceList() {
      this.traceInfo = {
        page_index: 1,
        page_size: 10,
        model: '',
        sort: ''
      }
      // this.maps.clear()
    },
    getTraceList(cb) {
      this.loadingFull = true
      apis
        .codeTrace(this.traceInfo)
        .then((res) => {
          this.loadingFull = false
          if (res.code === 200) {
            const arr = res.data.list.map((v) => {
              v.hasChildren = v.child_num > 0
              return v
            })
            cb && cb(arr, res.data.total)
          } else {
            this.$message.error(res.message || '获取防伪码批次失败')
          }
        })
        .catch((e) => {
          console.log(e)
          this.loadingFull = false
          this.$message.error('获取防伪码批次失败')
        })
    },
    getCreateCodeModel() {
      this.loadingFull = true
      apis
        .createCodeModel()
        .then((res) => {
          this.loadingFull = false
          if (res.code === 200) {
            this.codeModelList = Object.keys(res.data)
            // this.searchParams.model = this.codeModelList[0]
            this.getRtpList()
          } else {
            this.$message.error(res.message || '获取一键生成类型失败')
          }
        })
        .catch(() => {
          this.loadingFull = false
          this.$message.error('获取一键生成类型失败')
        })
    },
    // 导出
    submitCodeExport(id) {
      this.loadingFull = true
      apis
        .codeExport({ id })
        .then((res) => {
          this.loadingFull = false
          if (res.code === 200) {
            const exportA = document.createElement('a')
            exportA.setAttribute('href', res.data)
            exportA.setAttribute('download', '防伪码')
            exportA.click()
          } else {
            this.$message.error(res.message || '导出失败')
          }
        })
        .catch(() => {
          this.loadingFull = false
          this.$message.error('导出失败')
        })
    },
    // 删除批次
    submitDeleteTrace(id) {
      this.$confirm(
        `删除该批次下所有子码将会被删除, 确认继续删除?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.loadingFull = true
          apis.deleteTrace({ id }).then(res => {
            this.loadingFull = false
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.getRtpList()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          }).catch(() => {
            this.loadingFull = false
            this.$message.error('删除失败')
          })
        })
        .catch(() => {})
    },
    resetChildCode() {
      this.childCodeParent.clear()
      this.childCodeIsTrue = ''
      this.childCodeVis = false
    },
    submitChildCodeSet() {
      if (!this.childCodeIsTrue) {
        this.$message.error('请选择设置子码的真假')
        return false
      }
      const { data, parent } = this.childCodeParent.get('child')
      let { p_id } = data
      p_id = p_id || 0
      this.loadingFull = true
      apis
        .childIsTrue({ id: data.id, is_true: this.childCodeIsTrue })
        .then((res) => {
          this.loadingFull = false
          if (res.code === 200) {
            this.$message.success('设置成功')
            this.resetChildCode()
            if (+p_id === 0) {
              console.log(1)
              if (parent) {
                const i = this.codeList.findIndex(v => +v.id === +parent.id)
                this.$set(this.codeList[i], 'codeTree', [])
                this.$set(this.codeList[i], 'codeTotal', 0)
                const { row, ex } = this.expendMaps.get(parent.id)
                this.getCodeTrace(row, ex)
              } else {
                this.getSearchCode()
              }
            } else {
              const { tree, treeNode, resolve } = this.maps.get(p_id) // 根据p_id取出对应的节点数据
              this.$set(this.$refs.childTable.store.states.lazyTreeNodeMap, p_id, [])
              if (this.$refs.childTable2) {
                this.$set(this.$refs.childTable2.store.states.lazyTreeNodeMap, p_id, [])
              }
              this.getChildCode(tree, treeNode, resolve)
            }
          } else {
            this.$message.error(res.message || '设置失败')
          }
        })
        .catch((e) => {
          console.log(e)
          this.loadingFull = false
          this.$message.error('设置失败')
        })
    },
    // 设置真假
    submitCodeTrue(data, parent) {
      if (data.is_sell && +data.is_sell === 1) {
        this.$message.error('该防伪码绑定商品已出售, 不允许修改')
        return false
      }
      if (data.is_lowest === 1) {
        let { p_id } = data
        p_id = p_id || 0
        this.$confirm(
          `确认将防伪码设置为${data.is_true === 1 ? '真码' : '假码'}?`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
          .then(() => {
            this.loadingFull = true
            apis
              .childIsTrue({ id: data.id })
              .then((res) => {
                this.loadingFull = false
                if (res.code === 200) {
                  this.$message.success('设置成功')
                  if (+p_id === 0) {
                    if (parent) {
                      const i = this.codeList.findIndex(v => +v.id === +parent.id)
                      this.$set(this.codeList[i], 'codeTree', [])
                      this.$set(this.codeList[i], 'codeTotal', 0)
                      const { row, ex } = this.expendMaps.get(parent.id)
                      this.getCodeTrace(row, ex)
                    } else {
                      this.getSearchCode()
                    }
                  } else {
                    const { tree, treeNode, resolve } = this.maps.get(p_id) // 根据p_id取出对应的节点数据
                    this.$set(this.$refs.childTable.store.states.lazyTreeNodeMap, p_id, [])
                    this.getChildCode(tree, treeNode, resolve)
                  }
                } else {
                  this.$message.error(res.message || '设置失败')
                }
              })
              .catch((e) => {
                console.log(e)
                this.loadingFull = false
                this.$message.error('设置失败')
              })
          })
          .catch(() => {})
      } else {
        this.childCodeVis = true
        this.childCodeParent.set('child', { data, parent })
      }
    },
    // 获取字码
    getChildCode(tree, treeNode, resolve) {
      this.loadingFull = true
      const p_id = tree.id
      this.maps.set(p_id, { tree, treeNode, resolve })
      apis
        .childCode({ pid: tree.sort })
        .then((res) => {
          this.loadingFull = false
          if (res.code === 200) {
            res.data.forEach((v) => {
              v.hasChildren = v.child_num > 0
              v.p_id = p_id || 0
            })
            resolve(JSON.parse(JSON.stringify(res.data)))
          } else {
            this.$message.error(res.message || '获取子码失败')
          }
        })
        .catch(() => {
          this.loadingFull = false
          this.$message.error('获取子码失败')
        })
    },
    // 查看代理详情
    handleSeeMemberInfo(row) {
      this.memberInfo = row
      this.memberInfoVis = true
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.searchParams.page_size = limit
      this.searchParams.page_index = page
      this.getRtpList()
    },
    searchChangePagination(data) {
      const { page, limit } = data
      this.searchPageIndex = page
      this.searchPageSize = limit
      this.getSearchCode()
    },
    // 删除
    submitDeleteCode(data, parent) {
      if (data.get_child && data.get_child.length > 0) {
        this.$message.error('该防伪码下存在子码, 请先删除子码')
        return false
      }
      let { p_id } = data
      p_id = p_id || 0
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loadingFull = true
          apis
            .deleteCode({ id: data.id })
            .then((res) => {
              this.loadingFull = false
              if (res.code === 200) {
                this.$message.success('删除成功')
                if (+p_id === 0) {
                  if (parent) {
                    const i = this.codeList.findIndex(v => +v.id === +parent.id)
                    this.$set(this.codeList[i], 'codeTree', [])
                    this.$set(this.codeList[i], 'codeTotal', 0)
                    let num = this.codeList[i].num
                    this.$set(this.codeList[i], 'num', --num)
                    const { row, ex } = this.expendMaps.get(parent.id)
                    this.getCodeTrace(row, ex)
                  } else {
                    this.getSearchCode()
                  }
                } else {
                  const { tree, treeNode, resolve } = this.maps.get(p_id) // 根据p_id取出对应的节点数据
                  this.$set(this.$refs.childTable.store.states.lazyTreeNodeMap, p_id, [])
                  this.getChildCode(tree, treeNode, resolve)
                }
              } else {
                this.$message.error(res.message || '删除失败')
              }
            })
            .catch((e) => {
              console.log(e)
              this.loadingFull = false
              this.$message.error('删除失败')
            })
        })
        .catch(() => {})
    },
    submitCreateOne(id) {
      this.$confirm('确认生成单个防伪码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loadingFull = true
          apis
            .createOne({ pid: id })
            .then((res) => {
              this.loadingFull = false
              if (res.code === 200) {
                this.$message.success('生成防伪码成功')
                this.getRtpList()
              } else {
                this.$message.error(res.message || '生成防伪码失败')
              }
            })
            .catch(() => {
              this.loadingFull = false
              this.$message.error('生成防伪码失败')
            })
        })
        .catch(() => {})
    },
    resetCreateMany() {
      this.codeMany = {
        total: 1,
        grade: 1,
        num: 1
      }
      this.$refs.codeManyForm.resetFields()
      this.codeVis.many = false
    },
    submitCreateMany() {
      this.$refs.codeManyForm.validate((valid) => {
        if (valid) {
          this.loadingFull = true
          apis
            .createMany(this.codeMany)
            .then((res) => {
              this.loadingFull = false
              this.$message.success('一键生成成功')
              this.resetCreateMany()
              this.getRtpList()
            })
            .catch(() => {
              this.loadingFull = false
              this.$message.error('一键生成失败')
            })
        } else {
          return false
        }
      })
    },
    getRtpList() {
      this.loadingFull = true
      apis
        .rtpList(this.searchParams)
        .then((res) => {
          this.loadingFull = false
          if (res.code === 200) {
            res.data.list.forEach(v => {
              v.codeTree = []
              v.codeTotal = 0
            })
            this.codeList = res.data.list
            this.codeListTotal = res.data.total
          } else {
            this.$message.error(res.message || '获取列表失败')
          }
        })
        .catch(() => {
          this.loadingFull = false
          this.$message.error('获取列表失败')
        })
    }
  }
}
</script>
<style lang="scss" scoped>
#rtp_list {
  .tree_node_icons {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0;
    .tree_node_icon_active {
      background: #409eff !important;
    }
    .tree_node_icon {
      cursor: pointer;
      width: 25px;
      height: 25px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #ccc;
      color: #ffffff;
      margin-right: 15px;
      border-radius: 2px;
      font-size: 14px;
      &:hover {
        background: #409eff !important;
      }
    }
  }
  /deep/ .el-tree-node__expand-icon {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .tree_node {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    border-bottom: 1px solid #e6ebf5;
    .tree_node_code {
      flex: 1;
      overflow: hidden;
      height: 40px;
      line-height: 40px;
      margin: 0;
    }
  }
}
.no_float {
  &::after {
    content: "";
    display: block;
    clear: both;
  }
}
</style>
