<template>
  <div>
    <!--    表格导入-->
    <el-dialog v-model='showImport'
               append-to-body
               center
               title="数据表格导入"
               @close="close"
               width="45%">
      <div class='flex flex-center flex-col'>
        <div class="flex flex-center full-width flex-justify-start">
          <span class="bold mr-20">文件上传</span>
          <div>
            <uploads ref='upload' max="9" btn-text="点击进行文件上传" @before="before" @success="upload"
                     @error='loading = false'
                     :loading='loading'
                     :data='dept'
                     :action='action'
                     accept=".xlsx"/>
          </div>
          <div>
            <span class='bold ml-10 mr-10'>是否是汇总表</span>
            <el-switch v-model='gather'/>
          </div>
          <div class='flex flex-center' v-if='gather === false'>
            <span class='bold ml-10 mr-10'>项目所属机构:</span>
            <div>
              <el-autocomplete
                  v-model='deptName'
                  clearable
                  placeholder="快速搜索机构"
                  prefix-icon="Search"
                  :trigger-on-focus="false"
                  :fetch-suggestions="querySearchDept"
                  @select="handleSelectDept"
              />
            </div>
          </div>
        </div>
        <div class="flex flex-justify-start full-width">
          <span class="font-12 mt-10"
                style="color:#E24141">注意：文件格式需要为Excel表格，表格必须要有项目名称及责任单位名称两项内容，才能确保系统成功解析文件。</span>
        </div>
      </div>
      <el-divider/>
      <div class="hide-scrollbar full-width" style="height: 20vh;overflow-x: scroll" v-loading='loading'>
        <div v-if='attaches.length === 0' class='full-width flex flex-center '>
          <el-empty image-size='100'/>
        </div>
        <div class="flex flex-justify-between flex-center mt-5" v-for="item in attaches" :key="item">
          <span class="blue">{{ item.name }}</span>
          <el-icon color="#DCAE64" size="16px" @click="removeFile(item)">
            <CircleCloseFilled/>
          </el-icon>
        </div>
      </div>
      <div class="flex flex-center mt-20 mb-5">
        <base-button title="重置" type="0" icon="Refresh"/>
        <base-button class="ml-15" title="导入" icon="el-icon-upload" @click='importExcel'/>
      </div>
    </el-dialog>
    <!--    表格导出-->
    <el-dialog v-model='showExport'
               append-to-body
               center
               @close="close"
               title="数据表格导出"
               width="75%">
      <div class="flex flex-col">
        <el-autocomplete
            v-model="keyWords"
            clearable
            placeholder="字段信息快速搜索"
            prefix-icon="Search"
            :trigger-on-focus="false"
            :fetch-suggestions="querySearch"
            @select="handleSelect"
        />
        <div class="flex flex-wrap flex-align-center">
          <div class="flex flex-center padding radius box-shadow mr-20 mt-20 pointer"
               v-for="(item,index) in fieldType" :key='item.id'
               :class="item.count > 0 ? 'box-s' : 'box'"
               @click='switchTab(item,index)'>
            <div class="flex flex-col flex-center">
              <span class="bold font-16 text-center">{{ item.dictValue }}</span>
              <div class="flex flex-center">
                <el-icon color="#81D0B2">
                  <SuccessFilled/>
                </el-icon>
                <span class="grey-9 font-12">已选{{ item.count }}项目</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-divider/>
      <div v-loading='loading' class="hide-scrollbar full-width">
        <!--        <div v-if='attaches.length === 0' class='full-width flex flex-center '>-->
        <!--          <el-empty image-size='100'/>-->
        <!--        </div>-->
        <div class="flex flex-justify-start flex-center">
          <span class="bold grey ml-5 ">字段选择</span>
          <el-checkbox class='ml-20' @change='allChange'>全 选</el-checkbox>
          <div class='flex flex-center' v-if='selectIndex === 2'>
            <div class='bold ml-10 text-right' style='width: 80px'>筛选：</div>
            <el-select
                v-model="year"
                clearable
                placeholder="选择年份"
                style="width: 200px"
            >
              <el-option
                  v-for="item in years"
                  :key="item + `年`"
                  :label="item + `年`"
                  :value="item"
              />
            </el-select>

            <el-select
                v-model="season"
                clearable
                class='ml-20 mr-20'
                placeholder="选择季度"
                style="width: 200px"
            >
              <el-option
                  v-for="item in seasons"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
              />
            </el-select>

            <el-select
                v-if='season === "" '
                v-model="month"
                clearable
                placeholder="选择月份"
                style="width: 200px"
            >
              <el-option
                  v-for="item in 12"
                  :key="item + `月`"
                  :label="item + `月`"
                  :value="item"
              />
            </el-select>

            <el-button icon='el-icon-search' class='ml-20' type='primary' @click='search'>搜 索</el-button>
            <el-button icon='el-icon-delete' class='ml-20' type='primary' plain @click='resetKey'>清 空</el-button>
          </div>
        </div>
        <div class="flex flex-wrap" v-if='selectIndex !== -1' style="height: 300px;overflow-x: scroll">
          <div v-for="(item,index) in fieldType[selectIndex].params" :key='item.id'
               class="flex  padding pointer">
            <el-checkbox v-model=item.checked :label="item.code" size="large" @change='change(selectIndex,index)'>
              {{ item.dictValue }}
            </el-checkbox>
          </div>
        </div>
        <el-empty v-else description='点击上方按钮，选择字段'/>
      </div>
      <div class="flex flex-center mt-20 mb-5">
        <base-button title="重置" @click='resetParams' type="0" icon="Refresh"/>
        <base-button class="ml-15" title="导出表格" icon="el-icon-download" @click='exportExcel'/>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import BaseButton from '@/components/base-button.vue'
import uploads from '@/components/uploads.vue'
import { useStore } from '@/store/user.js'

export default {
  name: 'form_dialog',
  components: { BaseButton, uploads },
  setup () {
    const user = useStore()
    return { user }
  },
  props: {
    dialogType: {
      type: String,
      default: -1
    }
  },
  watch: {
    dialogType: {
      handler (val) {
        if (val === 0) {
          this.showImport = true
        } else if (val === 1) {
          this.getDict('params_type')
          this.showExport = true
        } else {
          this.showExport = false
          this.showImport = false
          this.loading = false
          this.deptName = ''
          this.attaches = []
        }
      },
      immediate: true
    },
    season: {
      handler (val) {
        if (val.length > 0) {
          this.month = ''
        }
      }
    }
  },
  data () {
    return {
      deptName: '',
      deptList: [],
      dept: null,
      loading: false,
      active: 0,
      checked: true,
      showImport: false,
      showExport: false,
      attaches: [],
      gather: false,
      action: '/api/wutong-parse-file/import-excel/v1/parse-excel',
      keyWords: '',
      code: '',
      fieldType: [],
      paramsList: [],
      checkList: [],
      selectIndex: -1,
      resultParams: [],
      inspectList: [],
      page: {
        current: 1,
        size: 10
      },
      years: [],
      year: '',
      seasons: [
        {
          name: '第一季度',
          value: 1
        },
        {
          name: '第二季度',
          value: 2
        },
        {
          name: '第三季度',
          value: 3
        },
        {
          name: '第四季度',
          value: 4
        }
      ],
      season: '',
      month: ''
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      const tmp = new Date().getFullYear()
      this.year = tmp
      for (let i = 0; i < tmp - 2018; i++) {
        const res = Number.parseInt(tmp) - i
        this.years.push(res)
      }
    },
    /**
     * 获取督查情况
     */
    getInspects (status) {
      const data = { status }
      this.$api.inspect.list(Object.assign(this.page, data)).then(res => {
        if (res.code === 200) {
          console.log(res)
        }
      })
    },
    getDict (code) {
      this.$api.common.dicList({ code }).then(res => {
        if (res.code === 200) {
          if (code === 'inspect_type') {
            this.inspectList = res.data
            this.getInspects(this.inspectList[0].dictKey)
          } else {
            const tmps = res.data.map(e => {
              e.isSelect = false
              e.count = 0
              e.parmas = []
              return e
            })
            this.fieldType = tmps
          }
        }
      })
    },
    close () {
      this.$emit('close')
    },
    upload (res) {
      this.attaches = res.fileList
      this.$message.success('操作成功')
      this.showImport = false
      this.loading = false
      this.deptName = ''
      this.close()
    },
    before (files) {
      this.attaches = files
    },
    removeFile (item) {
      this.attaches = this.attaches.filter(sub => sub.uid !== item.uid)
    },
    switchTab (item, index) {
      this.fieldType[index].isSelect = !this.fieldType[index].isSelect
      this.selectIndex = index
      if (index === 2) {
        this.$api.params.paramsList({
          type: this.fieldType[this.selectIndex].dictKey,
          year: this.year,
          season: this.season,
          month: this.month
        }).then(res => {
          if (res.code === 200) {
            this.parseList(res.data.records, index)
          }
        })
        return
      }
      this.$api.params.getListByKey({ type: this.fieldType[index].dictKey, export: 1 }).then(res => {
        if (res.code === 200) {
          this.parseList(res.data.records, index)
        }
      })
    },
    /**
     * 组装数据
     * @param list
     * @param index
     */
    parseList (list, index, reset = Boolean) {
      const tmps = list.map(e => {
        e.checked = reset ? false : this.fieldType[index].params === undefined ? false : this.fieldType[index].params.findIndex(sub => sub.id === e.id) > -1
        return e
      }).filter(sub => sub.code !== 'name')
      if (this.fieldType[index].params !== undefined && reset === false) {
        const d = tmps.filter(ele => {
          return this.fieldType[index].params.findIndex(sub => sub.id === ele.id) === -1
        })
        for (let i = 0; i < d.length; i++) {
          this.fieldType[index].params.push(d[i])
        }
      } else {
        this.fieldType[index].params = tmps
      }
      this.fieldType[index].count = this.fieldType[index].params.filter(e => e.checked).length
    },
    importExcel () {
      if (this.attaches && this.attaches.length === 0) {
        this.$message.error('请选择要上传的文件')
        return
      }
      if (this.gather) {
        this.action = '/api//wutong-parse-file/import-excel/v1/parse-summary-excel'
      } else {
        if (this.dept === null) {
          this.$message.error('请选择项目所属机构')
          return
        }
        this.action = '/api/wutong-parse-file/import-excel/v1/parse-excel'
      }
      this.loading = true
      this.$message.success('正在导入，请稍后...')
      if (this.user.info.viewStage === 1) {
        this.dept = Object.assign({}, this.dept, { isReport: 1 })
      } else {
        this.dept = Object.assign({}, this.dept, { isReport: 0 })
      }
      this.$refs.upload.submit()
    },
    change (parentIndex, index) {
      const tmp = this.fieldType[parentIndex].params.filter(e => e.checked)
      this.fieldType[parentIndex].count = tmp.length
      for (let i = 0; i < tmp.length; i++) {
        this.resultParams.push(tmp[i])
      }
    },
    allChange (res) {
      this.fieldType[this.selectIndex].params = this.fieldType[this.selectIndex].params.map(sub => {
        sub.checked = res
        return sub
      })
      const tmp = this.fieldType[this.selectIndex].params.filter(e => e.checked)
      this.fieldType[this.selectIndex].count = tmp.length
    },
    resetParams () {
      this.fieldType[this.selectIndex].params = this.fieldType[this.selectIndex].params.map(sub => {
        sub.checked = false
        return sub
      })
      this.fieldType[this.selectIndex].count = 0
    },
    exportExcel () {
      const params = this.fieldType.filter(sub => sub.params).map(sub => sub.params)
      const tmps = [].concat.apply([], params)
      const tmpsList = tmps.filter(sub => sub.checked)
      if (tmpsList && tmpsList.length > 0) {
        const result = tmpsList.map(sub => sub.code).join(',')
        this.loading = true
        this.$emit('export', 'name,' + result)
      } else {
        this.$message.error('未选择任何字段进行导出')
      }
      this.attaches = []
    },
    querySearchDept (key, cb) {
      if (key && key.length === 0) {
        return
      }
      setTimeout(() => {
        const parentId = [0, 2].includes(this.user.info.viewStage) ? this.user.info.parentDeptId : this.user.info.deptId
        this.$api.system.getDeptLazy({ deptName: key, parentId }).then(res => {
          if (res.code === 200) {
            const tmp = res.data.map(sub => {
              const item = { value: sub.deptName, label: sub.deptName, deptId: sub.id, areaCode: sub.areaCode }
              return item
            })
            cb(tmp)
          }
        })
      }, 500)
    },
    querySearch (string, cb) {
      if (string && string.length === 0) {
        return
      }
      setTimeout(() => {
        this.$api.params.getParamByName({ dictValue: string }).then(res => {
          if (res.code === 200) {
            const tmp = res.data.records.map(sub => {
              const item = { value: sub.dictValue, label: sub.dictValue }
              return Object.assign(sub, item)
            })
            cb(tmp)
          }
        })
      }, 500)
    },
    handleSelectDept (item) {
      this.dept = item
    },
    handleSelect (item) {
      const sub = item
      sub.search = true
      sub.checked = true
      const index = this.fieldType.findIndex(e => e.dictKey === sub.type)
      if (index > -1) {
        this.fieldType[index].count++
        if (this.fieldType[index].params === undefined) {
          this.fieldType[index].params = []
          this.fieldType[index].params.push(sub)
        } else {
          const subIndex = this.fieldType[index].params.findIndex(ele => ele.id === sub.id)
          if (subIndex > -1) {
            this.fieldType[index].params[subIndex].checked = true
          } else {
            this.fieldType[index].params.push(sub)
          }
        }
        this.$message.success(item.dictValue + '已勾选成功')
        this.fieldType[index].params.count = this.fieldType[index].params.filter(sub => sub.checked).length
      }
    },
    resetKey () {
      this.year = ''
      this.season = ''
      this.month = ''
    },
    search () {
      this.$api.params.paramsList({
        type: this.fieldType[this.selectIndex].dictKey,
        year: this.year,
        season: this.season,
        month: this.month
      }).then(res => {
        if (res.code === 200) {
          this.parseList(res.data.records, this.selectIndex, true)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.pic {
  width: 196px;
  height: 154px;
  margin-top: -20px;
}

.box-s {
  border: 1px solid #AC9A7C;
  width: 120px;
  height: 50px;
  color: #D1A55F;
}

.box {
  width: 120px;
  height: 50px;
  border: 1px solid transparent;
  background: #F1F2F7;
  color: #707070;
}
</style>
