<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="container_item">
        <span class="item_text">{{$t('mechanism.orgCode')}}：</span>
        <el-input v-model="query.orgCode" placeholder="" class="filter-item input_item"   />
      </div>
      <div class="container_item">
        <span class="item_text">{{$t('mechanism.orgName')}}：</span>
        <el-input v-model="query.orgName" placeholder="" class="filter-item input_item"    />
      </div>
      <el-button v-waves class="filter-item" style="margin-right: 10px!important;" type="primary" icon="el-icon-my-search" @click="handleSearch">
        {{ $t('table.search') }}
      </el-button>
      <el-button v-waves class="filter-item" style="margin-right: 10px!important;" type="primary" icon="el-icon-my-reset" @click="handleReset">
        {{ $t('table.reset') }}
      </el-button>
      <el-button v-if="permission.includes('mechanism_add')" v-waves class="filter-item" type="primary" icon="el-icon-my-add" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>
    <div class="wrapper_table">
      <el-table
        :data="tableData"
        fit
        stripe
        highlight-current-row
        style="width: 100%;"
        :header-cell-class-name="headerStyle"
        :max-height="tableHeight"
      >
        <el-table-column prop="orgCode" :label="$t('mechanism.orgCode')"  align="left" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column prop="orgName" :label="$t('mechanism.orgName')" align="left" min-width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="prName" :label="$t('mechanism.prName')" align="left" ></el-table-column>
        <el-table-column prop="orgTreePcode" :label="$t('mechanism.orgTreePcode')" align="left" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <div>
                {{scope.row.orgTreePcode==0?'':getPcode(scope.row.orgTreePcode,orgList)}}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="regAddress" :label="$t('mechanism.regAddress')" align="left" min-width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="regTel" :label="$t('mechanism.regTel')" align="left" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="emailAddress" :label="$t('mechanism.emailAddress')" align="left" min-width="120" show-overflow-tooltip ></el-table-column>
        <el-table-column :label="$t('table.actions')" align="left" width="210"  class-name="small-padding ">
          <template slot-scope="{row}">
              <div class="flex_d">
                    <el-button v-if="permission.includes('mechanism_update')" type="text" size="mini" icon="el-icon-my-modify" @click="handleUpdate(row)">
                    {{ $t('table.modify') }}
                    </el-button>
                    <el-button v-if="permission.includes('mechanism_del')" size="mini" type="text" icon="el-icon-my-del-y" @click="handleDelete(row)">
                    {{ $t('table.delete') }}
                    </el-button>
                    <el-button v-if="permission.includes('mechanism_quota_reappraisal')" size="mini" type="text" icon="el-icon-my-edcp" @click="handleQuotaRet(row)">
                    {{ $t('table.quotaReassessment') }}
                    </el-button>
              </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="getData" />
    <el-dialog
      :title="handleType==1? '新增': handleType==2 ?'修改' : '删除'"
      :visible.sync="dialogFormVisible"
      v-el-drag-dialog
      :close-on-click-modal="false"
      width="960px">
        <div class="addflex">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form ref="dataForm" :model="temp" label-position="right" label-width="100px" :disabled="handleType === 3" >
                <el-form-item :label="$t('mechanism.orgCode')+'：'" :class="{'unabled is-disabled': handleType == 3 || handleType==2, 'require': handleType === 1}">
                  <el-input v-model="temp.orgCode"  style="width:319px" :disabled="handleType==2"/>
                </el-form-item>
                <el-form-item :label="$t('mechanism.orgName')+'：'" :class="{'unabled is-disabled': handleType === 3, 'require': handleType !== 3}">
                  <el-input v-model="temp.orgName"  style="width:319px"  />
                </el-form-item>

                <el-form-item :label="$t('mechanism.reportCurrency')+'：'" >
                  <el-select v-model="temp.reportCurrency" placeholder="请选择" style="width:319px">
                    <el-option
                      v-for="item in currencyList"
                      :key="item.currencyCode"
                      :label="item.currencyCode"
                      :value="item.currencyCode">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label="$t('mechanism.localCurrency')+'：'">
                  <!-- <el-input v-model="temp.orgName"  style="width:319px"  /> -->
                  <el-select v-model="temp.localCurrency" placeholder="请选择" style="width:319px">
                    <el-option
                      v-for="item in currencyList"
                      :key="item.currencyCode"
                      :label="item.currencyCode"
                      :value="item.currencyCode">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label="$t('mechanism.baseCurrency')+'：'" :class="{'unabled is-disabled': handleType === 3, 'require': handleType !== 3}">
                  <!-- <el-input v-model="temp.orgName"  style="width:319px"  /> -->
                  <el-select v-model="temp.baseCurrency" placeholder="请选择" style="width:319px">
                    <el-option
                      v-for="item in currencyList"
                      :key="item.currencyCode"
                      :label="item.currencyCode"
                      :value="item.currencyCode">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label="$t('mechanism.countryCode')+'：'" :class="{'unabled is-disabled': handleType === 3, 'require': handleType !== 3}">
                  <el-select v-model="temp.countryCode" placeholder="请选择" style="width:319px">
                    <el-option
                      v-for="item in countryList"
                      :key="item.id"
                      :label="item.countryCode"
                      :value="item.countryCode">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label="$t('mechanism.timeZone')+'：'">
                  <!-- <el-input v-model="temp.timeZone"  style="width:319px"  /> -->
                  <el-select v-model="temp.timeZone" placeholder="请选择" style="width:319px">
                    <el-option
                      v-for="item in timeZoomList"
                      :key="item.value"
                      :label="item.key"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label="$t('mechanism.enterPname')+'：'">
                  <treeselect
                    style="width:319px"
                    v-model="temp.orgPcode"
                    :options="orgList"
                    :normalizer="normalizer"
                    placeholder="请选择"
                    :disabled="handleType === 3"
                    @select="selectHandle"
                  />
                </el-form-item>
                <el-form-item :label="$t('mechanism.orgTreePcode')+'：'">
                  <el-input v-model="temp.orgPcode" style="width:319px" disabled/>
                </el-form-item>

              </el-form>
            </el-col>
            <el-col :span="12">
              <el-form ref="dataForm"  :model="temp" label-position="right" label-width="120px" :disabled="handleType === 3">
                <el-form-item :label="$t('mechanism.prName')+'：'" :class="{'unabled is-disabled': handleType === 3, 'require': handleType !== 3}">
                  <el-input v-model="temp.prName"  style="width:319px"  />
                </el-form-item>
                <el-form-item :label="$t('mechanism.prJobNumber')+'：'" :class="{'unabled is-disabled': handleType === 3, 'require': handleType !== 3}">
                    <el-input v-model="temp.prJobNumber"  style="width:319px"  />
                </el-form-item>
                <el-form-item :label="$t('mechanism.prPhone')+'：'" >
                    <el-input v-model="temp.prPhone"  style="width:319px"  />
                </el-form-item>
                <el-form-item :label="$t('mechanism.regTel')+'：'" >
                    <el-input v-model="temp.regTel"  style="width:319px"  />
                </el-form-item>
                <el-form-item :label="$t('mechanism.emailAddress')+'：'">
                    <el-input v-model="temp.emailAddress"  style="width:319px"  />
                </el-form-item>
                <el-form-item :label="$t('mechanism.regAddress')+'：'">
                    <el-input v-model="temp.regAddress"   style="width:319px"/>
                </el-form-item>
                <el-form-item :label="$t('mechanism.maintenanceuser')+'：'" class="unabled is-disabled">
                    <el-input v-model="temp.updateUserName" disabled  style="width:319px"  />
                </el-form-item>
                <el-form-item :label="$t('mechanism.maintenancetime')+'：'" class="unabled is-disabled">
                    <el-input v-model="temp.updateTime"  disabled  style="width:319px" />
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </div>
      <div slot="footer" class="dialog-footer" style="padding-right:26px">
        <template v-if="handleType === 3">
          <el-button v-waves class="filter-item flex_align" type="primary" icon="el-icon-my-delete" @click="sbumitData">
              {{ $t('table.delete') }}
          </el-button>
        </template>
        <template v-else>
          <el-button v-waves class="filter-item flex_align" type="primary" icon="el-icon-my-tijiao" @click="sbumitData">
              {{ $t('table.sbumit') }}
          </el-button>
        </template>
        <el-button v-waves class="filter-item flex_align" type="primary" icon="el-icon-my-quxiao" @click="dialogFormVisible=false">
            {{ $t('table.cancel') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog'
import { mapGetters } from 'vuex'
import http from '@/api/http'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { isvalidatemobile, validateEmail, validateLocalMobile } from '@/utils/validate.js';
import { checkArr } from './check.js'
export default {
  name: '',
  components: { Pagination, Treeselect },
  directives: { waves, elDragDialog },
  computed: {
    ...mapGetters([
      'permission',
    ])
  },
  data() {
    return {
      total: 0,
      query:{},
      listRole:[],
      tableData:[],
      pageSize:20,
      pageNum:1,
      orgList:[],
      form:{},
      temp: {
        orgCode: undefined,
        orgName: undefined,
        reportCurrency: undefined,
        localCurrency: undefined,
        baseCurrency: undefined,
        countryCode: undefined,
        timeZone: undefined,
        orgTreePcode: undefined,
        enterPname: undefined,
        prName: undefined,
        prJobNumber: undefined,
        prPhone: undefined,
        regTel: undefined,
        emailAddress: undefined,
        regAddress: undefined,
        updateUserName: undefined,
        updateTime: undefined,
      },
      checkArr: checkArr,
      dialogFormVisible: false,
      dialogStatus: '',
      handleType:'1',
      tableHeight: 0,
      chpwdVisible:false,
      pwdChangeData:{},
      multipleSelection:[],
      optionsList:[],
      currencyList:[],
      countryList: [],
      timeZoomList: []
    }
  },
  created() {
    this.getData()
    this.queryAllTree();//
    this.getCurrency();
    this.getCountryCode();

    this.getSysDictionaryList(); // 时区下拉列表
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 240
    })
  },
  methods: {
    // 额度重评
    // 参数orgTreeCode//机构树形结构的编码)
    handleQuotaRet(row) {
      http.post('/sys/org/reProcess', { orgTreeCode: row.orgTreeCode }).then((res) => {
        this.$message.success('操作成功')
      }).catch(() => {})
    },

    // 10、获取字典项列表(内存中获取)
    getSysDictionaryList() {
      http.post('/sys/dictionary/getSysDictionaryList', { dictType: 1 }).then((res) => {
        this.timeZoomList = res.data || []
      })
    },
    // 转换菜单数据结构
    normalizer(node) {
      if (node.childs && !node.childs.length) {
        delete node.childs;
      }
      return {
        id: node.orgCode,
        label: node.orgName,
        children: node.childs
      };
    },
    selectHandle(value) {
      // console.log(value);
      this.temp.enterPname = value.orgName
    },
    // 查询机构树信息
    queryAllTree() {
      http.post('/sys/org/queryAllTree', {}).then((res) => {
        console.log(res.data);
        this.orgList = res.data || []
      })
    },
    getData() {
      this.queryAllTree();
      http.post(`/sys/org/queryLists`,{cpage:this.pageNum,pageSize:this.pageSize,...this.query}).then((res)=>{
          this.tableData = res.data.list;
          this.total = res.data.total || 0;
      }).catch(err=>{});
    },
    // getOptions(){
    //   http.post(`/cust/queryLists`,{cpage:1,pageSize:99}).then((res)=>{
    //     this.optionsList = res.data.list;
    //   }).catch(err=>{});
    // },

    // 查询币种信息列表
    getCurrency(){
      http.post(`/share/currency/queryList`,{cpage:1,pageSize:99}).then((res)=>{
        this.currencyList = res.data.list;
      }).catch(()=>{});
    },
    // 查询国家
    getCountryCode(){
      http.post(`/share/CountryCode/queryList`,{cpage:1,pageSize:99}).then((res)=>{
        this.countryList = res.data.list;
      }).catch(()=>{});
    },
    sysTime(){
      http.post(`/sys/config/serverDate`).then((res)=>{

      }).catch(err=>{});
    },
    handleSearch(){
      this.pageNum = 1
      this.getData()
    },

    handleUpdate(row) {
      this.queryAllTree();
      Object.keys(this.temp).forEach((v) => {
        this.temp[v] = row[v] ? row[v] : undefined
        if (v === 'orgTreePcode') {
          this.temp[v] = this.temp[v] == 0 ? undefined : this.temp[v]
        }
      })
      this.temp = Object.assign(this.temp, { id: row.id })
      let orgPcode = this.getPcode(this.temp.orgTreePcode,this.orgList)
      this.$set(this.temp,'orgPcode',orgPcode)
      console.log('this.temp', this.temp);
      this.handleType = 2
      this.dialogFormVisible = true
    },

    // 删除机构信息
    handleDelete(row) {
      console.log(row);
      this.queryAllTree();
      Object.keys(this.temp).forEach((v) => {
        this.temp[v] = row[v] ? row[v] : undefined
        if (v === 'orgTreePcode') {
          this.temp[v] = this.temp[v] == 0 ? undefined : this.temp[v]
        }
      })
      this.temp = Object.assign(this.temp, { id: row.id })
      let orgPcode = this.getPcode(this.temp.orgTreePcode,this.orgList)
      this.$set(this.temp,'orgPcode',orgPcode)
      this.handleType = 3
      this.dialogFormVisible = true
      console.log(this.temp);
    },
    getPcode(code,list){
      for(let item of list ){
        if(item.orgTreeCode == code){
          return item.orgCode
        }else if(item.childs&&item.childs.length>0){
          this.getOrgPcode(code,item.childs)
        }
      }
    },
    handleCreate() {
      this.sysTime();
      this.queryAllTree();
      if (this.handleType === 2 || this.handleType === 3) {
        Object.keys(this.temp).forEach((v) => {
          this.temp[v] = undefined
        })
      }
      this.handleType = 1
      this.dialogFormVisible = true
    },
    sbumitData() {

      // let { prPhone, emailAddress, regTel } = this.temp
      if (this.handleType !== 3) {
        let { maintenanceuser, maintenancetime, enterPname, ...checkTemp } = this.temp
        for(let i=0;i<Object.keys(checkTemp).length;i++) {
          // console.log(i,Object.keys(checkTemp)[i]);
          const tarKey = Object.keys(checkTemp)[i]
          if (tarKey === 'prPhone') {
            if (this.temp[tarKey]) {
              if (isvalidatemobile(this.temp[tarKey])[0]) {
                this.$message.error(`负责人${isvalidatemobile(this.temp[tarKey])[1]}`)
                return
              }
            }
          } else if (tarKey === 'regTel') {
            if (this.temp[tarKey]) {
              if (!validateLocalMobile(this.temp[tarKey])) {
                this.$message.error('市话输入规则{3,4}-{7,8}')
                return
              }
            }
          } else if (tarKey === 'emailAddress') {
            if (this.temp[tarKey]) {
              if (!validateEmail(this.temp[tarKey])) {
                this.$message.error('统一邮箱地址错误')
                return
              }
            }
            // if (!this.temp[tarKey]) {
            //   this.$message.error('统一邮箱不能为空')
            //   return
            // }
          } else {
            if (tarKey === 'orgCode' || tarKey === 'orgName' || tarKey === 'baseCurrency' || tarKey === 'prName' || tarKey === 'countryCode') {
              if (!this.temp[tarKey]) {
                let mes = this.checkArr.find(ele => ele.key === tarKey).label
                this.$message.error(`${mes}不能为空`)
                return
              }
            }

          }
        }
      }
      let returnMes = ''
      let params = {}
      let path = ''
      switch(this.handleType) {
        case 1: { // 新增
          path = '/sys/org/create'
          params = Object.assign({ ...this.temp }, { status: 1 })
          let { orgPcode } = params
          // console.log('orgTreePcode', orgTreePcode);
          if (!orgPcode) {
            params = Object.assign(params, { orgTreePcode: 0 })
          }else{
            params.orgTreePcode =  this.getOrgPcode(params.orgPcode,this.orgList)
          }
          returnMes = '新增'
          break;
        }
        case 2: { // 修改
          path = '/sys/org/update'
          params = Object.assign({ ...this.temp }, { status: 1 })
          let { orgPcode } = params
          if (!orgPcode) {
            params = Object.assign(params, { orgTreePcode: 0 })
          }else{
            params.orgTreePcode =  this.getOrgPcode(params.orgPcode,this.orgList)
          }
          returnMes = '修改'
          break;
        }
        case 3: { // 删除
          path = '/sys/org/delete'
          params = Object.assign({}, { id: this.temp.id })
          returnMes = '删除'
          break;
        }
        default:
          break;
      }

      // console.log(params);
      http.post(path, params).then((res)=>{
        this.$message.success(`${returnMes}成功`);
        this.getData();
        this.queryAllTree();
        this.dialogFormVisible = false;
        Object.keys(this.temp).forEach((v) => {
          this.temp[v] = undefined
        })
      }).catch(()=>{});
    },
    getOrgPcode(code,list){
      for(let item of list ){
        if(item.orgCode == code){
          return item.orgTreeCode
        }else if(item.childs&&item.childs.length>0){
          this.getOrgPcode(code,item.childs)
        }
      }
    },
    handleReset() {
      this.pageNum = 1
      Object.keys(this.query).forEach((v) => {
        this.query[v] = undefined
      })
      this.getData()
    },

    headerStyle() {
      return 'tableStyle'
    },
    authorization(){

    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  }
}
</script>
<style scope lang="scss">
.vue-treeselect {
   &.require {
    border: 1px solid #267CD5;
  }
  &.unabled {
    .vue-treeselect__control {
      box-shadow: 1px 1px 4px 0px rgb(0 0 0 / 20%) inset;
      background: none !important;
      opacity: 0.5;
      .vue-treeselect__value-container {
        .vue-treeselect__input-container {
          .vue-treeselect__input {
            cursor: not-allowed !important;
          }
        }
      }
    }
  }
  &.vue-treeselect--disabled {
    .vue-treeselect__control {
      background: #e6e6e6 !important;
      .vue-treeselect__value-container {
        color: #707070 !important;
        .vue-treeselect__single-value {
          line-height: 28px;
          padding-left: 4px;
          padding-right: 4px;
          font-family: 'SourceHanSansCN';
          color: #707070 !important;
        }
        .vue-treeselect__placeholder {
          line-height: 28px;
          font-size: 13px;
        }
        .vue-treeselect__input-container {
          .vue-treeselect__input {
            height: 28px;
          }
        }
      }
      .vue-treeselect__control-arrow {
        opacity: 1 !important;
      }
    }
  }
  .vue-treeselect__control {
    height: 28px;
    line-height: 28px;
    font-size: 13px;
    border-radius: 2px;
    box-shadow: 1px 1px 3px 0px rgb(0 0 0 / 40%) inset;
    background: #FFFFFF;
    padding-left: 10px;
    padding-right: 6px;
    .vue-treeselect__value-container {
      color: #212121;
      .vue-treeselect__single-value {
        line-height: 28px;
        padding-left: 4px;
        padding-right: 4px;
        font-family: 'SourceHanSansCN';
      }
      .vue-treeselect__placeholder {
        line-height: 28px;
        font-size: 13px;
        color: #C0C4CC;
        font-family: 'SourceHanSansCN';
      }
      .vue-treeselect__input-container {
        .vue-treeselect__input {
          height: 28px;
        }
      }
    }
    .vue-treeselect__control-arrow-container {
      .vue-treeselect__control-arrow {
        width: 10px;
        height: 10px;
        color: #12579D;
      }
    }
  }
}
  .el-table__header-wrapper{
    border-radius: 10px 10px 0 0;
  }
  .userinfo{
    margin: 20px 50px;
    width: 464px;
    // height: 313px;
    background: rgba(212,235,254,.1);
    border: 1px solid rgba(61,85,150,.1);
    p{
      margin-left: 20px;
      font-size: 14px;
      font-family: "SourceHanSansCN";
      font-weight: 500;
      color: #212121;
      border-left: 3px solid #3D5596;
      padding-left: 8px;
    }
    .input_item{
      width: 319px !important;
    }
    .tab{
      margin: 0 30px 20px;
    }
  }
  .userinfo ::v-deep .el-form-item__label{
    font-size: 14px!important;
    color: #212121 !important;
  }
  .addflex{
    display: flex;
    padding: 30px 30px 0px 30px;
    justify-content: center;
  }
  .customClass {
    .el-message-box__btns {
      .el-button {
        width: 70px;
        height: 30px;
        background:url('~@/assets/images/btn4x.png') no-repeat;
        background-size: 100% 100%;
        font-size: 12px;
        border: none;
        color: #FFFFFF;
        text-shadow: 0px 1px 1px #001D40;
        span {
          position: relative;
          bottom: 1px;
        }
      }
    }
  }
</style>
