<template>
  <div class='wraper'>
    <div class='page_left'>
      <el-tree
        :data='treeData'
        :props='defaultProps'
        highlight-current
        ref='tree'
        :node-key="'continentCode'"
        current-node-key=''
        @node-click='handleNodeClick'>
        <span class='custom-tree-node' slot-scope='{ node }'>
          <span v-html='node.label'></span>
        </span>
      </el-tree>
    </div>
    <div class='page_right'>
      <el-form :inline='true' size='mini' :model='searchForm' class='search_form'>
        <el-form-item label='国家代码'>
          <el-select v-model='searchForm.countryCode' filterable clearable placeholder='国家代码'>
            <el-option
              v-for='(item,index) in countryList'
              :key='index'
              :label="item.nameCn + '(' + item.countryCode + ')'"
              :value='item.countryCode'>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='州/省编码'>
          <el-input
            v-model='searchForm.provinceCode'
            placeholder='中文名称'
            style='width: 120px'
            clearable></el-input>
        </el-form-item>
        <el-form-item label='州/省英文名称'>
          <el-input
            v-model='searchForm.province'
            placeholder='英文名称'
            style='width: 120px'
            clearable></el-input>
        </el-form-item>
        <el-form-item label=''>
          <el-button type='primary' @click='getList()'>查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type='success' @click='addDialog(1)'>新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type='danger' @click='deleteSection()'>删除</el-button>
        </el-form-item>
      </el-form>
      <div class='my-table-cont my-flex-1'>
        <my-table
          :sourceData='userData'
          ref='multipleTable'
          :selection='true'
          :tableColumns='tableColumns'
          @selectionChange='selectionChange'
          @current-change='currentTabFn'></my-table>
      </div>
      <pagination
        :setValue='setpaginationOptions'
        :options='paginationOptions' />
    </div>
    <!-- 弹出层 -->
    <el-dialog
      :close-on-click-modal='false'
      :title="is_title === 1 ? '新增' : '编辑'"
      :visible.sync='dialogVisible'
      width='700px'>
      <el-form
        label-position='right'
        label-width='130px'
        size='mini'
        :inline='true'
        :model='addcurrencyform'
        :rules='addrules'
        ref='addcurrencyform'>
        <el-row type='flex' class='row-bg' justify='center'>
          <el-col>
            <el-form-item label='国家代码' prop='countryCode'>
              <el-select v-model='addcurrencyform.countryCode' filterable placeholder='国家代码' style='width: 164px'>
                <el-option
                  v-for='(item,index) in countryList'
                  :key='index'
                  :label="item.nameCn + '(' + item.countryCode + ')'"
                  :value='item.countryCode'>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label='州/省编码' prop='provinceCode'>
              <el-input
                v-model='addcurrencyform.provinceCode'
                placeholder='请输入州/省编码'></el-input>
            </el-form-item>
            <el-form-item label='州/省英文名称' prop='province'>
              <el-input
                v-model='addcurrencyform.province'
                placeholder='请输入州/省英文名称'></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot='footer'>
        <el-button
          @click='dialogVisible = false'
          size='mini'
          style='width: 130px'>
          取消
        </el-button>
        <el-button
          type='primary'
          @click='addCurrency()'
          size='mini'
          style='width: 130px'>
          确认
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { get, post } from '../../common/api/axios'
import MyTable from '@/common/components/base/tableView.vue'

export default {
  name: 'system_abbreviation',
  components: {
    MyTable,
  },
  data() {
    return {
      paginationOptions: {
        currentPage: 1,
        total: 0,
        pageSize: 100,
      },
      is_title: 1,
      userData: [],
      dialogVisible: false,
      addcurrencyform: {
        id: '',
        countryCode: '',
        provinceCode: '',
        province: '',
      },
      continentList: [],
      countryList: [],
      selection: [],
      addcurrencyform2: null,
      formId: null,
      addrules: {
        countryCode: [
          {
            required: true,
            message: '请输入国家代码',
            trigger: 'blur',
          },
        ],
        province: [
          {
            required: true,
            message: '请输入州/省名称',
            trigger: 'blur',
          },
        ],
        provinceCode: [
          {
            required: true,
            message: '请输入州/省编码',
            trigger: 'change',
          },
        ],
      },
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'continentName',
      },
      searchForm: {
        countryCode: '',
        province: '',
        provinceCode: '',
      },
    }
  },
  created() {
    this.loadTreeData()
    this.addcurrencyform2 = JSON.parse(JSON.stringify(this.addcurrencyform))
    get('common/commonCountryCode/allContinentlist').then((res) => {
      this.continentList = res.data
    })
  },
  computed: {
    tableColumns() {
      return [
        {
          label: '国家代码',
          key: 'countryCode',
        },
        {
          label: '国家名称',
          key: 'nameCn',
        },
        {
          label: '州/省编码',
          key: 'provinceCode',
        },
        {
          label: '州/省英文名',
          key: 'province',
        },
        {
          label: '相关操作',
          key: '',
          width: 80,
          render: (item) => (
            <div>
              {(
                <span class='icon-view icon-edit-view' title='编辑'>
                  <i
                    class='el-icon-edit'
                    onClick={() => this.addDialog(2, item)}></i>
                </span>
              )}
              {(
                <span class='icon-view icon-del-view' title='删除'>
                  <i
                    class='el-icon-delete-solid'
                    onClick={() => this.deleteSection(item)}></i>
                </span>
              )}
            </div>
          ),
        },
      ]
    },
  },
  methods: {
    loadTreeData() {
      get('common/commonCountryCode/findByContinent').then((res) => {
        this.treeData = [
          ...res.data,
        ]
        if (this.treeData.length > 0) {
          this.treeStatus = this.treeData[0].continentCode
        }
        this.$nextTick(() => {
          this.getCountryList()
          this.$refs.tree.setCurrentKey(this.treeStatus)
        })
      })
    },
    handleNodeClick(data) {
      this.treeStatus = data.continentCode
      this.searchForm.countryCode = ''
      this.getCountryList()
      // this.getList()
    },
    getCountryList() {
      post('common/commonCountryCode/list_page', {
        currentPage: 1,
        pageSize: 1000,
        continentCode: this.treeStatus,
      }).then(res => {
        if (res.code === 200) {
          this.countryList = res.data.records
          if (this.countryList.length > 0 && this.treeStatus === 'NA') {
            this.searchForm.countryCode = 'US'
          }
          this.getList()
        }
      })
    },
    setpaginationOptions(opt) {
      for (const key in opt) {
        this.paginationOptions[key] = opt[key]
      }
      this.getList()
    },
    currentTabFn(val) {
      if (val) {
        this.formId = val.id
      } else {
        this.formId = null
      }
    },
    addDialog(i, v = null) {
      if (i === 2) {
        if (v) this.formId = v.id
        if (!this.formId) return this.$message('请勾选至少一条记录')
        this.selectSection()
      } else {
        this.$nextTick(() => {
          this.addcurrencyform = JSON.parse(
            JSON.stringify(this.addcurrencyform2),
          )
        })
      }
      this.is_title = i
      this.dialogVisible = true
      if (this.$refs.addcurrencyform) this.$refs.addcurrencyform.resetFields()
    },
    addCurrency() {
      this.$refs.addcurrencyform.validate((valid) => {
        if (valid) {
          if (this.is_title === 1) {
            this.addSection()
          } else {
            this.upSection()
          }
        } else {
          return false
        }
      })
    },
    /**
     * @description {查询}
     */
    getList() {
      const {
        pageSize,
        currentPage,
      } = this.paginationOptions
      post('common/commonProvinceData/list_page', {
        pageSize,
        currentPage,
        ...this.searchForm,
        continentCode: this.treeStatus,
      }).then((res) => {
        if (res.code === 200) {
          this.userData = res.data.records
          this.paginationOptions.total = res.data.total
        } else {
          this.$alert(res.message, '错误提示', {
            dangerouslyUseHTMLString: true,
          })
        }
      })
    },
    /**
     * @description {部门职员查询}
     */
    selectSection() {
      const url = `common/commonProvinceData/get?id=${this.formId}`
      get(url).then((res) => {
        if (res.code === 200) {
          const data = res.data
          for (const item in data) {
            if (data[item] && !Array.isArray(data[item])) {
              data[item] = data[item] + ''
            }
          }
          this.addcurrencyform = Object.assign({}, data)
          this.is_title = 2
          this.dialogVisible = true
        } else {
          this.$alert(res.message, '错误提示', {
            dangerouslyUseHTMLString: true,
          })
        }
      })
    },
    /**
     * @description {修改}
     */
    upSection() {
      const url = 'common/commonProvinceData/update'
      post(url, this.addcurrencyform).then((res) => {
        if (res.code === 200) {
          this.dialogVisible = false
          this.$message({
            message: '修改成功',
            type: 'success',
          })
          this.getList(this.currentPage)
        } else {
          this.$alert(res.message, '错误提示', {
            dangerouslyUseHTMLString: true,
          })
        }
      })
    },
    /**
     * @description{新增}
     */
    addSection() {
      const url = 'common/commonProvinceData/add'
      post(url, this.addcurrencyform).then((res) => {
        if (res.code === 200) {
          this.dialogVisible = false
          this.$message({
            message: '添加成功',
            type: 'success',
          })
          this.getList(this.currentPage)
        } else {
          this.$alert(res.message, '错误提示', {
            dangerouslyUseHTMLString: true,
          })
        }
      })
    },
    selectionChange(selection) {
      this.selection = selection
    },
    /**
     * @description{删除}
     */
    deleteSection(v) {
      let arr = []
      if (v) {
        arr.push(v)
      } else {
        arr = this.selection
      }
      const leng = arr.length
      if (leng === 0) return this.$message('请勾选至少一条记录')
      let ids = []
      ids = arr.map((v) => {
        return v.id
      })
      ids = ids.join()
      this.$confirm('确定删除选中的信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const url = `common/commonProvinceData/delete?ids=${ids}`
          get(url).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
              this.getList(this.currentPage)
            } else {
              this.$alert(res.message, '错误提示', {
                dangerouslyUseHTMLString: true,
              })
            }
          })
        })
        .catch(() => {
        })
    },
  },
}
</script>
<style lang='scss' scoped>
.wraper {
  height: 100%;
  display: flex;
  overflow: hidden;

  .page_left {
    width: 200px;
    min-width: 200px;
    background: #fff;
    border-radius: 5px;
    margin-right: 10px;
  }

  .page_right {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #fff;
    border-radius: 5px;
    overflow: hidden;
  }

  .search_form {
    margin-top: 5px;
    margin-left: 10px;
  }

  .search_form > .el-form-item {
    margin-bottom: 5px;
  }

  .search_form {
    margin-top: 5px;
    margin-left: 10px;
  }

  .content {
    max-height: 61vh;
    overflow: auto;
  }
}
</style>
