<template>
  <div class="wraper">
    <div class="page_left">
      <el-tree
        :data="treeData"
        :props="defaultProps"
        highlight-current
        :node-key="'continentCode'"
        current-node-key=""
        @node-click="handleNodeClick">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span v-html="node.label"></span>
          <span>({{ data.quantity }})</span>
        </span>
      </el-tree>
    </div>
    <div class="page_right">
      <el-form
        :inline="true"
        size="mini"
        :model="searchForm"
        class="search_form">
        <el-form-item label="国家代码" prop="">
          <el-input
            v-model="searchForm.countryCode"
            placeholder="国家代码"
            style="width: 120px"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="国家中文名称" prop="">
          <el-input
            v-model="searchForm.nameCn"
            placeholder="中文名称"
            style="width: 120px"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="国家英文名称" prop="">
          <el-input
            v-model="searchForm.nameEn"
            placeholder="英文名称"
            style="width: 120px"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button :loading="searchLoading" 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
            :loading="delLoading"
            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-input
                v-model="addcurrencyform.countryCode"
                placeholder="请输入国家代码"></el-input>
            </el-form-item>
            <el-form-item label="速卖通代码" prop="aeCountryCode">
              <el-input
                v-model="addcurrencyform.aeCountryCode"
                placeholder="请输入国家代码"></el-input>
            </el-form-item>
            <el-form-item label="洲" prop="continentCode">
              <el-select
                v-model="addcurrencyform.continentCode"
                style="width: 164px"
                placeholder="请选择洲"
                filterable>
                <el-option
                  v-for="item in continentList"
                  :key="item.code"
                  :label="item.cName + '(' + item.code + ')'"
                  :value="item.code">
                  {{ item.cName }}({{ item.code }})
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="需要州/省简称" prop="needProviceAbbr">
              <el-radio-group v-model="addcurrencyform.needProviceAbbr">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="中文名称" prop="nameCn">
              <el-input
                v-model="addcurrencyform.nameCn"
                placeholder="请输入国家中文名称"></el-input>
            </el-form-item>
            <el-form-item label="英文名称" prop="nameEn">
              <el-input
                v-model="addcurrencyform.nameEn"
                placeholder="国家英文名称"></el-input>
            </el-form-item>
            <el-form-item label="国际电话区号" prop="telephoneAreaCode">
              <el-input
                v-model="addcurrencyform.telephoneAreaCode"
                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: 'basics_countryCode',
  components: {
    MyTable
  },
  data() {
    return {
      paginationOptions: {
        currentPage: 1,
        total: 0,
        pageSize: 100
      },
      searchLoading: false,
      delLoading: false,
      is_title: 1,
      userData: [],
      dialogVisible: false,
      addcurrencyform: {
        id: '',
        countryCode: '',
        nameCn: '',
        nameEn: '',
        needProviceAbbr: '1'
      },
      continentList: [],
      selection: [],
      addcurrencyform2: null,
      formId: null,
      addrules: {
        countryCode: [
          {
            required: true,
            message: '请输入国家代码',
            trigger: 'blur'
          }
        ],
        aeCountryCode: [
          {
            required: true,
            message: '请输入速卖通代码',
            trigger: 'blur'
          }
        ],
        continentCode: [
          {
            required: true,
            message: '请输入洲',
            trigger: 'change'
          }
        ],
        needProviceAbbr: [
          {
            required: true,
            message: '请选择',
            trigger: 'change'
          }
        ],
        nameCn: [
          {
            required: true,
            message: '请输入中文名称',
            trigger: 'blur'
          }
        ],
        nameEn: [
          {
            required: true,
            message: '请输入英文名称',
            trigger: 'blur'
          }
        ]
      },
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'continentName'
      },
      searchForm: {
        countryCode: '',
        nameCn: '',
        nameEn: ''
      }
    }
  },
  created() {
    this.getList(1)
    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: 'aeCountryCode'
        },
        {
          label: '洲',
          key: 'continentCode',
          render: (item) => item.nameCn + '(' + item.nameEn + ')'
        },
        {
          label: '国家中文名称',
          key: 'nameCn'
        },
        {
          label: '国家英文名称',
          key: 'nameEn'
        },
        {
          label: '国际电话区号',
          key: 'telephoneAreaCode'
        },
        {
          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) => {
        const totalData = res.data.reduce((acc, cur) => {
          return acc + cur.quantity
        }, 0)
        this.treeData = [
          {
            continentCode: '',
            quantity: totalData,
            continentName: '全部'
          },
          ...res.data
        ]
      })
    },
    handleNodeClick(data) {
      this.treeStatus = data.continentCode
      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
      this.searchLoading = true
      post('common/commonCountryCode/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
            })
          }
          this.searchLoading = false
        })
        .catch(() => {
          this.searchLoading = false
        })
    },
    /**
     * @description {部门职员查询}
     */
    selectSection() {
      const url = `common/commonCountryCode/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/commonCountryCode/update'
      post(url, this.addcurrencyform).then((res) => {
        if (res.code === 200) {
          this.dialogVisible = false
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this.loadTreeData()
          this.getList(this.currentPage)
        } else {
          this.$alert(res.message, '错误提示', {
            dangerouslyUseHTMLString: true
          })
        }
      })
    },
    /**
     * @description{新增}
     */
    addSection() {
      const url = 'common/commonCountryCode/add '
      post(url, this.addcurrencyform).then((res) => {
        if (res.code === 200) {
          this.dialogVisible = false
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.loadTreeData()
          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(() => {
          if (!v) this.delLoading = true
          const url = `common/commonCountryCode/delete?ids=${ids}`
          get(url).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })

              this.loadTreeData()
              this.getList(this.currentPage)
            } else {
              this.$alert(res.message, '错误提示', {
                dangerouslyUseHTMLString: true
              })
            }
            if (!v) this.delLoading = false
          })
        })
        .catch(() => {
          if (!v) this.delLoading = false
        })
    }
  }
}
</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>
