<template>
  <a-modal
    centered
    class="marketingDivisionSetEdit-modal"
    :footer="null"
    :maskClosable="false"
    :title="modalTit"
    v-model="isShow"
    @cancle="isShow=false"
    width="800px">
    <!-- 表单 -->
    <div>
      <a-form-model
        id="marketingDivisionSetEdit-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
      >
        <a-form-model-item label="分区名称" prop="subareaName">
          <a-input
            id="marketingDivisionSetEdit-subareaName"
            :maxLength="30"
            v-model="form.subareaName"
            @change="filterEmpty"
            placeholder="请输入分区名称(最多30个字符)"
            allowClear />
        </a-form-model-item>
        <a-form-model-item label="省份/市">
          <div class="tree-node" id="treeNode">
            <div class="tree-box" v-for="item in addrProvinceList" :key="item.id">
              <div class="tree-parent">
                <span>
                  <a-checkbox style="width: 100%;" :indeterminate="item.indeterminate" v-model="item.checked" @change="onChange(item,$event)">
                    {{ item.name }}
                    <!-- <i style="font-size: 12px;color: #999;font-style: normal;">（已选 {{ item.children | hasCheckChild }} 个市区）</i> -->
                  </a-checkbox>
                </span>
                <span @click="expend(item)"><a-icon :title="item.isOpen==0?'展开':'收起'" :type="item.isOpen==0?'plus-square':'minus-square'" /></span>
              </div>

              <!-- 子级 -->
              <div v-show="item.isOpen==1" class="tree-child">
                <div v-for="child in item.children" :key="child.id">
                  <a-checkbox v-model="child.checked" style="width: 100%;" @change="onChange(child,$event,item)">
                    {{ child.name }}
                  </a-checkbox>
                </div>
              </div>
            </div>
          </div>
        </a-form-model-item>
      </a-form-model>
      <div class="btn-cont">
        <a-button type="primary" id="marketingDivisionSetEdit-modal-save" @click="handleSave">保存</a-button>
        <a-button id="marketingDivisionSetEdit-modal-back" @click="isShow = false" style="margin-left: 15px;">返回列表</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script>
import { STable, Upload } from '@/components'
import Editor from '@/components/WEeditor'
import { getArea } from '@/api/data'
import { subareaSaveSubareaArea, subareaFindBySn } from '@/api/subarea'
export default {
  name: 'MarketingDivisionSetEditModal',
  components: { STable, Upload, Editor },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    itemId: {
      type: [Number, String],
      default: ''
    },
    nowData: {
      type: Object,
      default: null
    }
  },
  computed: {
    modalTit () {
      return (this.itemId ? '编辑' : '新增') + '分区'
    }
  },
  filters: {
    hasCheckChild: function (value) {
      return value.filter(item => item.checked).length
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
      },
      form: {
        subareaName: '' // 分区名称
      },
      rules: {
        subareaName: [
          { required: true, message: '请输入分区名称', trigger: 'blur' }
        ]
      },
      addrProvinceList: [], //  省下拉
      subareaAreaList: []
    }
  },
  methods: {
    filterEmpty () {
      let str = this.form.subareaName
      str = str.replace(/\ +/g, '')
      str = str.replace(/[ ]/g, '')
      str = str.replace(/[\r\n]/g, '')
      this.form.subareaName = str
    },
    onChange (item, e, parent) {
      console.log(item, `checked = ${e.target.checked}`)
      item.checked = e.target.checked
      item.noSave = false
      // 父级
      if (item.type == 2) {
        item.children && item.children.map(d => {
          d.checked = item.checked
        })
        item.indeterminate = false
      }
      // 子级
      if (item.type == 3) {
        // 父级节点
        const hasCheckd = parent.children.filter(k => k.checked)
        // 是否全选
        parent.checked = hasCheckd.length == parent.children.length
        parent.children.map(d => d.noSave = parent.checked)
        parent.indeterminate = !parent.checked
      }
      this.addrProvinceList = JSON.parse(JSON.stringify(this.addrProvinceList))
    },
    // 展开收起
    expend (item) {
      if (item.children && item.children.length == 0) {
        item.isOpen = 1
        this.getArea('city', item, 1)
      } else {
        item.isOpen = !item.isOpen
      }
    },
    //  省/市/区
    getArea (leve, item, openType) {
      let params
      if (leve == 'province') {
        params = { type: '2' }
      } else {
        params = { parentId: item.areaSn, type: leve == 'city' ? '3' : '4' }
      }
      getArea(params).then(res => {
        if (res.status == 200) {
          if (leve == 'province') {
            this.addrProvinceList = res.data || []
            this.addrProvinceList.map(item => {
              item.noSave = true
              item.checked = false
              item.children = []
              item.indeterminate = false
            })
            // 编辑时获取已选数据
            if (this.itemId) {
              this.getChecked()
            }
            document.getElementById('treeNode').scrollTop = 0
          } else if (leve == 'city') {
            item.children = res.data || []
            item.children.map(d => {
              // 编辑时回显
              if (this.itemId && openType == 0) {
                d.checked = !!this.subareaAreaList.find(o => o.areaSn == d.areaSn)
                d.noSave = false
              } else {
                d.checked = item.checked
                d.noSave = true
              }
            })

            // 首次加载子级
            if (openType == 1) {
              this.addrProvinceList = JSON.parse(JSON.stringify(this.addrProvinceList))
            } else {
              item.isOpen = 1
              item.indeterminate = true
            }
          }
        } else {
          if (leve == 'province') {
            this.addrProvinceList = []
          } else if (leve == 'city') {
            item.children = []
            item.isOpen = 0
          }
        }
      })
    },
    // 过滤数据
    filterData (list) {
      list.map(item => {
        if (item.checked && !item.noSave) {
          this.subareaAreaList.push({
            areaSn: item.areaSn,
            areaName: item.name,
            areaType: item.type,
            areaParentSn: item.parentId
          })
        } else {
          if (item.children && item.children.length) {
            this.filterData(item.children)
          }
        }
      })
    },
    //  保存
    handleSave () {
      const _this = this
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(_this.form))
          this.subareaAreaList = []
          this.filterData(this.addrProvinceList)
          console.log(this.subareaAreaList)
          // 编辑
          if (this.itemId) {
            formData.subareaSn = this.itemId
          }
          formData.subareaAreaList = this.subareaAreaList
          console.log(formData, 'formData')
          subareaSaveSubareaArea(formData).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$emit('ok')
              _this.isShow = false
            }
          })
        } else {
          return false
        }
      })
    },
    // 编辑
    getChecked () {
      subareaFindBySn({ sn: this.itemId }).then(res => {
        console.log(res.data)
        this.form.subareaName = res.data.subareaName
        this.subareaAreaList = res.data.subareaAreaList
        this.form.subareaSn = res.data.subareaSn
        this.form.id = res.data.id
        // 回显数据
        this.showChecked()
      })
    },
    showChecked () {
      // 省回显
      this.addrProvinceList.map(item => {
        item.checked = !!this.subareaAreaList.find(d => d.areaSn == item.areaSn)
        item.noSave = false
        item.indeterminate = false
      })
      // 市回显
      const hasCity = this.nowData.subareaAreaList.filter(item => item.citySubareaAreaList && item.citySubareaAreaList.length)
      console.log(hasCity, 'hasCity.nowData')
      hasCity.map(item => {
        // 省
        const pre = this.addrProvinceList.find(k => k.areaSn == item.areaSn)
        // 获取子级
        this.getArea('city', pre, 0)
      })
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.form.subareaName = ''
        this.form.subareaSn = ''
        delete this.form.id
      } else {
        this.getArea('province')
      }
    }
  }
}
</script>

<style lang="less">
  .marketingDivisionSetEdit-modal{
    .ant-modal-body {
    	padding: 40px 40px 24px;
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
    .tree-node{
      height: 300px;
      overflow: auto;
      .tree-box{
        .tree-parent{
          display: flex;
          align-items: center;
          border-bottom: 1px solid #eee;
          padding: 0 10px;
          > span{
            margin:0 5px;
            &:first-child{
              flex-grow: 1;
            }
            &:last-child{
              cursor: pointer;
            }
          }
        }
        .tree-child{
          padding: 10px 10px 10px 35px;
          display: flex;
          align-items: center;
          flex-wrap:wrap ;
          > div{
            margin:0 5px;
          }
        }
      }

    }
  }
</style>
