<template>
  <div class="subscribe-config">
    <div class="sub-title">订阅设置</div>
    <div class="sub-content">
      <!-- <div class="item">
        <div class="item-label item-label-required">区域：</div>
        <div class="item-value" @click="clickErea">
          <el-input class="custom-long-input" v-model="areaStr" readonly unselectable="on"></el-input>
        </div>
      </div> -->
      <div class="item">
        <div class="item-label item-label-required">区域：</div>
        <div class="item-value">
          <AreaCityCountryCascader
            ref="areaCityCountrySub"
            stopDropdown
            showSelected
            showCount
            :areaCount="areaCount"
            :initMap="regionMapData"
            @onClick="onAreaSelectClick"
            @change="onAreaCityCountryChange"
            @exceed="onExceedChange"
          >
            <div slot="header"></div>
          </AreaCityCountryCascader>
        </div>
      </div>
      <div class="item">
        <div class="item-label item-label-required">采购单位类型：</div>
        <div class="item-value" @click="dialog.buyClass = true">
          <el-input
            class="custom-long-input"
            v-model="buyClassStr"
            readonly
            unselectable="on"
          ></el-input>
        </div>
      </div>
      <div class="item">
        <div class="item-label item-label-required">信息类型：</div>
        <div class="item-value" @click="dialog.infoType = true">
          <el-input
            class="custom-long-input"
            v-model="infoTypeStr"
            readonly
            unselectable="on"
          ></el-input>
        </div>
      </div>
      <div class="item-other">
        <div class="item-label">项目匹配：</div>
        <div class="item-value item-other-value">
          <el-switch
            @change="switchProjectMatch($event)"
            v-model="projectMatchData"
            :width="44"
            :active-value="1"
            :inactive-value="0"
            active-text="关"
            inactive-text="开"
            active-color="#2cb7ca"
            inactive-color="#bfbfbf"
          >
          </el-switch>
          <p class="math-tips">
            开启后，系统将根据你订阅的关键词自动匹配出相关联的项目，并将相关连项目的后续动态在超级订阅内一并推送。
          </p>
        </div>
      </div>
      <div class="item-other">
        <div class="item-label">关键词匹配方式：</div>
        <div class="item-value item-other-value">
          <el-radio-group
            v-model="matchWayData"
            @change="chooseMatchWay($event)"
          >
            <div class="radio-item">
              <el-radio name="matchway" :label="1">按标题匹配</el-radio>
            </div>
            <div>
              <el-radio name="matchway" :label="2">按全文匹配</el-radio>
            </div>
          </el-radio-group>
          <p class="math-tips">会产生无效信息，请根据需要选择</p>
        </div>
      </div>
    </div>
    <!-- 区域选择dialog -->
    <el-dialog
      custom-class="sub-dialog nesting-dialog r70"
      :visible.sync="dialog.area"
      :close-on-click-modal="false"
      :show-close="false"
      center
      width="460px"
      v-component-change-mount="{ selector: '.drawer-dialog' }"
    >
      <AreaSelect
        :initCityMap="areaData"
        :showSelectResult="true"
        :areaCount="areaCount"
        :canSetCityCount="canSetCityCount"
        :showSelectedDetail="false"
        @onCancel="dialog.area = false"
        @onConfirm="saveAreaData"
      >
        <template #update-tips>
          <span @click="onClickUpdateTip" v-if="!entStatus"
            >超出已购买省份数量，您可前往升级超级订阅＞
          </span>
        </template>
      </AreaSelect>
    </el-dialog>
    <!-- 采购单位行业dialog -->
    <el-dialog
      custom-class="sub-dialog nesting-dialog r70"
      :visible.sync="dialog.buyClass"
      :close-on-click-modal="false"
      :show-close="false"
      center
      width="460px"
      v-component-change-mount="{ selector: '.drawer-dialog' }"
    >
      <BuyClassSelect
        :initCate="buyerClassData"
        :otherMatch="otherBuyerClassData"
        getContainer=".drawer-dialog"
        @onCancel="dialog.buyClass = false"
        @onConfirm="saveBuyClassData"
        @onOtherConfirm="saveOtherBuyClass"
      >
        <div slot="header">选择采购单位类型</div>
      </BuyClassSelect>
    </el-dialog>
    <!-- 信息类型dialog -->
    <el-dialog
      custom-class="sub-dialog nesting-dialog r70"
      :visible.sync="dialog.infoType"
      :close-on-click-modal="false"
      :show-close="false"
      center
      width="460px"
      v-component-change-mount="{ selector: '.drawer-dialog' }"
    >
      <InfoTypeSelect
        :initInfoType="infoTypeData"
        @onCancel="dialog.infoType = false"
        @onConfirm="saveInfoTypeData"
      >
        <div slot="header">选择信息类型</div>
      </InfoTypeSelect>
    </el-dialog>
    <el-dialog
      :visible.sync="dialog.areaMap"
      title="超出可选省份数量"
      :show-close="false"
      class="tip-dialog"
      width="380px"
      top="30vh"
      center
      v-component-change-mount="{ selector: '.drawer-dialog' }"
    >
      <div>
        可选：<span class="highlight-text">{{ areaCount }}个省</span
        >，如需增加省份数量，您可前往升级超级订阅。
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.stop="goUpdateVip">去升级</el-button>
        <el-button @click="dialog.areaMap = false">取 消</el-button>
      </div>
    </el-dialog>
    <popupBox
      ref="popupBox"
      text="如需修改区域，请联系企业管理员修改分发设置区域。"
      title="不支持修改区域"
      :appendtoBody="false"
    ></popupBox>
  </div>
</template>
<script>
import { Switch, Input, RadioGroup, Radio, Button, Dialog } from 'element-ui'
import AreaSelect from '@/components/selector/AreaSelector'
import BuyClassSelect from '@/components/selector/BuyerclassSelector'
import InfoTypeSelect from '@/components/selector/InfoTypeSelector'
import popupBox from '@/components/common/popupBox'
import AreaCityCountryCascader from '@/components/selector-cascader/AreaCityCountryCascader.vue'
import { userRule, entBaseInfo } from '@/api/modules'
import { openSelfLink } from '@/utils/'
export default {
  name: 'sub-config',
  props: {
    projectMatch: [String, Number, Boolean],
    otherBuyerClass: [String, Number, Boolean],
    matchWay: [String, Number, Boolean],
    area: Object,
    buyerClass: Array,
    infoType: Array,
    areaCount: Number,
    canSetCityCount: Number,
    regionMap: Object
  },
  components: {
    [Switch.name]: Switch,
    [Input.name]: Input,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Button.name]: Button,
    [Dialog.name]: Dialog,
    AreaSelect,
    BuyClassSelect,
    InfoTypeSelect,
    popupBox,
    AreaCityCountryCascader
  },
  data() {
    return {
      areaStr: '',
      buyClassStr: '',
      infoTypeStr: '',
      projectMatchData: this.projectMatch,
      matchWayData: this.matchWay,
      otherBuyerClassData: this.otherBuyerClass,
      areaData: this.area,
      buyerClassData: this.buyerClass,
      infoTypeData: this.infoType,
      dialog: {
        area: false,
        buyClass: false,
        infoType: false,
        areaMap: false
      },
      timeout: null,
      entStatus: false,
      districtMapData: {},
      areaMapData: this.area,
      regionMapData: this.regionMap
    }
  },
  watch: {
    projectMatch(n) {
      this.projectMatchData = n
    },
    otherBuyerClass(n) {
      this.otherBuyerClassData = n
    },
    matchWay(n) {
      this.matchWayData = n
    },
    area(n) {
      this.areaData = n
      this.initData()
    },
    buyerClass(n) {
      this.buyerClassData = n
      this.initData()
    },
    infoType(n) {
      this.infoTypeData = n
      this.initData()
    },
    regionMap(n) {
      this.regionMapData = n
    }
  },
  computed: {
    formatAreaMap() {
      const original = this.areaData
      // 原二级数据结构为{福建：['福州', '厦门', '宁德']}
      // 现数据结构为三级 需进行处理
      if (Object.keys(original).length > 0) {
        const obj = {}
        for (const province in original) {
          let cityMap = {}
          if (Array.isArray(original[province])) {
            original[province].forEach((city) => {
              cityMap[city] = []
            })
          } else {
            cityMap = original[province]
          }
          obj[province] = cityMap
        }
        return obj
      } else {
        return original
      }
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    debounce(fn, delay) {
      if (this.timeout) {
        clearTimeout(this.timeout)
      }
      this.timeout = setTimeout(() => {
        fn()
      }, delay)
    },
    onClickUpdateTip() {
      const routeUrl = this.$router.resolve({
        path: '/free/svip/buy?type=upgrade'
      })
      openSelfLink(routeUrl)
    },
    clickErea() {
      this.debounce(() => {
        entBaseInfo({}).then((res) => {
          if (
            res.data.vip_power === 1 ||
            res.data.member_power === 1 ||
            res.data.user_power === 1
          ) {
            // 企业授权
            this.entStatus = true // 切换身份为 企业身份下
            userRule().then((res_) => {
              if (res_.data) {
                // 设置了区域
                this.$refs.popupBox.isshow = true
              } else {
                this.dialog.area = true
              }
            })
          } else {
            // 非企业授权
            this.dialog.area = true
          }
        })
      }, 200)
    },
    initData() {
      // this.formatterArea(this.area)
      this.formatterBuyerClass(this.buyerClass)
      this.formatterInfoType(this.infoType)
    },
    // 处理区域数据
    formatterArea(area = {}) {
      if (area && Object.keys(area).length > 0) {
        const provinceArr = []
        let areaArr = []
        for (const key in area) {
          provinceArr.push({
            province: key,
            citys: area[key]
          })
        }
        provinceArr.forEach((province, i) => {
          const cityArr = []
          let pStr = ''
          province.citys.forEach((city, ii) => {
            cityArr.push(city)
          })
          if (cityArr.length === 0) {
            pStr = province.province
          } else {
            pStr = province.province + '(' + cityArr.join('、') + ')'
          }
          areaArr.push(pStr)
        })
        areaArr = areaArr.join('、')
        this.areaStr = areaArr
      } else {
        this.areaStr = '全国'
      }
    },
    formatterBuyerClass(data = []) {
      if (data && data.length > 0) {
        this.buyClassStr =
          data.join('、') + (this.otherBuyerClassData ? '、匹配未分类行业' : '')
      } else {
        this.buyClassStr =
          '全部' + (this.otherBuyerClassData ? '、匹配未分类类型' : '')
      }
    },
    formatterInfoType(data = []) {
      if (data && data.length > 0) {
        this.infoTypeStr = data.join('、')
      } else {
        this.infoTypeStr = '全部类型'
      }
    },
    // 切换项目匹配按钮
    switchProjectMatch(event) {
      this.projectMatchData = event
      this.saveCommonData()
    },
    // 关键词匹配方式
    chooseMatchWay(event) {
      this.matchWayData = event
      this.saveCommonData()
    },
    // 冒泡区域修改数据
    saveAreaData(data) {
      this.areaData = data
      // this.formatterArea(data)
      this.dialog.area = false
      this.saveCommonData()
    },
    // 冒泡采购单位行业数据及匹配未分类行业数据
    saveBuyClassData(data) {
      this.buyerClassData = data
      this.formatterBuyerClass(data)
      this.saveCommonData()
      this.dialog.buyClass = false
    },
    // 冒泡未匹配采购单位行业
    saveOtherBuyClass(data) {
      this.otherBuyerClassData = data.selected ? 1 : 0
      this.formatterBuyerClass(this.buyerClassData)
      this.saveCommonData()
    },
    // 冒泡信息类型数据
    saveInfoTypeData(data) {
      this.infoTypeData = data
      this.formatterInfoType(data)
      this.saveCommonData()
      this.dialog.infoType = false
    },
    saveCommonData() {
      this.$emit('update', {
        // area: this.areaData,
        area: this.areaMapData,
        buyerClass: this.buyerClassData,
        infotype: this.infoTypeData,
        projectmatch: this.projectMatchData,
        matchway: this.matchWayData,
        otherbuyerclass: this.otherBuyerClassData,
        district: this.districtMapData,
        regionMap: this.regionMapData
      })
    },
    // 省市区组件回调数据
    onAreaCityCountryChange(data) {
      const { area, district, regionMap } = data
      this.areaMapData = area
      this.districtMapData = district
      this.regionMapData = regionMap
      this.saveCommonData()
    },
    // 区域选择超出冒泡事件
    onExceedChange() {
      this.dialog.areaMap = true
    },
    async onAreaSelectClick() {
      const { data } = await entBaseInfo()
      if (
        data.vip_power === 1 ||
        data.member_power === 1 ||
        data.user_power === 1
      ) {
        // 企业授权
        const { data: flag } = await userRule()
        if (flag) {
          this.$refs.popupBox.isshow = true
        } else {
          this.$refs.areaCityCountrySub.toggleSelect()
        }
      } else {
        this.$refs.areaCityCountrySub.toggleSelect()
      }
    },
    // 去升级
    goUpdateVip() {
      window.open('/swordfish/page_big_pc/free/svip/buy?type=upgrade')
    }
  }
}
</script>
<style lang="scss" scoped>
.subscribe-config {
  background: #fff;

  .sub-title {
    padding: 26px 30px;
    font-size: 18px;
    color: #1d1d1d;
    line-height: 28px;
    border-bottom: 1px solid #ececec;
  }

  .sub-content {
    padding: 20px 0;
  }

  .item {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;
  }

  .item-label {
    margin-right: 8px;
    min-width: 120px;
    height: 40px;
    color: #1d1d1d;
    font-size: 14px;
    line-height: 40px;
    text-align: right;
  }

  .item-label-required:before {
    content: '*';
    color: #f56c6c;
    margin-right: 2px;
  }

  .item-value {
    width: 352px;
  }

  .custom-long-input {
    width: 352px;
  }

  .item-other {
    display: flex;
    justify-content: center;
    margin-bottom: 10px;
  }

  .item-other-value {
    margin-top: 8px;
  }

  .math-tips {
    margin-top: 4px;
    font-size: 12px;
    color: #999999;
    line-height: 20px;
  }

  .radio-item {
    margin-bottom: 10px;
  }

  // element-ui样式修改
  ::v-deep {
    .custom-long-input .el-input__inner {
      font-size: 14px;
      color: #2cb7ca;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      border-color: #ececec;
    }

    .el-loading-spinner .circular {
      width: 22px;
      height: 22px;
    }

    .el-loading-spinner {
      margin-top: -11px;
    }

    .el-input__inner {
      background: #fff;
      cursor: pointer;
    }

    .el-switch {
      position: relative;
    }

    .el-switch__label--left {
      position: absolute;
      left: 6px;
      top: 0;
      color: #fff;
      z-index: 9;
      font-size: 12px;
    }

    .el-switch__label--right {
      position: absolute;
      right: 6px;
      top: 0;
      color: #fff;
      z-index: 9;
      font-size: 12px;
    }

    .el-switch__label * {
      font-size: 12px;
    }

    .el-switch,
    .el-switch__core {
      height: 22px;
      line-height: 22px;
    }

    .el-switch__core:after {
      width: 18px;
      height: 18px;
    }

    .el-switch.is-checked .el-switch__core::after {
      margin-left: -18px !important;
    }

    .el-radio {
      color: #1d1d1d;
      font-size: 14px;
    }

    .el-radio__inner {
      width: 20px;
      height: 20px;
    }

    .el-radio__input.is-checked .el-radio__inner {
      border: 0;
      background: transparent;
      width: 20px;
      height: 20px;
      background: url('~@/assets/images/icon-checked.png') no-repeat center
        center;
      background-size: contain;
    }

    .el-radio__inner::after {
      background: transparent;
    }

    .el-radio__input.is-checked + .el-radio__label {
      color: #1d1d1d;
    }

    .el-radio__inner:hover {
      border-color: #ececec;
    }
    .s-header {
      display: none;
    }
    .area-city-country {
      padding: 0 !important;
    }
    .el-select {
      width: 100%;
      .el-input__inner {
        height: 40px;
        line-height: 40px;
      }
      .select-prefix {
        height: 38px;
        line-height: 38px;
      }
    }
  }
}
</style>
