<template>
<div>
  <el-button type="default" size="mini" @click="onShow">{{$t('编 辑')}}</el-button>
  <el-drawer :title="$t(`编辑员工`)" direction="rtl" append-to-body :visible.sync="dialogFormVisible" size="800px" @close="$refs.form.clearValidate()" :show-close="false">
    <div class="drawer__panel">
      <el-row :gutter="20">
        <el-form :model="form" size="small" :rules="rules" ref="form" label-position="right" :label-width="tool.onlyZh('100px')">
          <el-row>
            <el-col  :span="24">
              <el-form-item :label="$t(`编号`)+':'" prop="hrcode">
                <el-input v-model="form.hrcode" :placeholder="$t(`编号`)" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="24">
              <el-form-item :label="$t(`性别`)">
                <el-select v-model="form.sex" style="width:100%" :placeholder="$t('请选择')">
                  <el-option
                    v-for="item in sys_options"
                    :key="item.index"
                    :label="$t(item.value)"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col  :span="24">
              <el-form-item :label="$t(`姓名`)+':'" prop="name">
                <el-input v-model="form.name" :placeholder="$t(`姓名`)" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="24">
              <el-form-item :label="$t(`电子邮箱`)+':'" prop="email">
                <el-input v-model="form.email" :placeholder="$t(`电子邮箱`)" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="24">
              <el-form-item :label="$t(`身份证号`)+':'">
                <el-input v-model="form.idcard" :placeholder="$t(`身份证号`)" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="24">
              <el-form-item :label="$t(`部门`)+':'" prop="depname">
                <el-popover
                  placement="bottom"
                  width="400"
                  trigger="click"
                  v-model="visible">
                  <el-tree
                    :data="deplist"
                    node-key="id"
                    default-expand-all
                    highlight-current
                    :expand-on-click-node="false"
                    @node-click="nodeClick"
                  >
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span>{{ node.label }}</span>
                    </span>
                  </el-tree>
                  <el-input slot="reference" v-model="form.depname" readonly :placeholder="$t('请选择')" autocomplete="off"></el-input>
                </el-popover>
              </el-form-item>
            </el-col>
            <el-col  :span="24">
              <el-form-item :label="$t(`办公电话`)+':'">
                <el-input v-model="form.officetelephone" :placeholder="$t(`办公电话`)" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>

            <el-col  :span="24">
              <el-form-item :label="$t(`职位`)+':'">
                <el-input v-model="form.position" :placeholder="$t(`职位`)" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="24">
              <el-form-item :label="$t(`汇报对象`)+':'">
                <selectMenber :reporthrname="form.reporthrname" @selectMenber="selectMenber"  @clearMenber="form.reporthrname = '';form.reporthrid = ''"></selectMenber>
              </el-form-item>
            </el-col>
            <el-col :span="24" >
              <el-form-item :label="$t(`状态`)+':'">
                <el-radio-group v-model="form.status">
                  <el-radio :label="0">{{ $t('在职') }}</el-radio>
                  <el-radio :label="1">{{ $t('离职') }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col  :span="5" style="height:51px">
              <el-form-item>
                <el-checkbox v-model="form.isleader" :false-label="0" :true-label="1">{{ $t('是否部门负责人') }}</el-checkbox>
              </el-form-item>
            </el-col>
            <el-col  :span="5">
              <el-form-item>
                <el-checkbox v-model="form.isworker" :false-label="0" :true-label="1">{{ $t('是否服务人员') }}</el-checkbox>
              </el-form-item>
            </el-col>

            <el-col  :span="5">
              <el-form-item>
                <el-checkbox v-model="form.isuppictured" :false-label="0" :true-label="1">{{ $t('是否上图员') }}</el-checkbox>
              </el-form-item>
            </el-col>
            <el-col  :span="5">
              <el-form-item>
                <el-checkbox v-model="form.issalehr" :false-label="0" :true-label="1" disabled>{{ $t('是否业务员') }}</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.issalehr == '1'">
            <el-col :span="24">
              <el-form-item :label="$t('业务员')" style="font-weight: bold">
                <addSalers :name="form.name" @salerInfo="salerInfo" :data="salerList"></addSalers>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.issalehr == '1'">
            <el-col :span="23" :offset="1">
              <tableNewLayout :layout="tablecols" :data="salerList" :opwidth="200" height="450px" :width="true" :custom="true" fixedName="operation">
                <template v-slot:customcol="scope">
                  <p v-if="scope.column.columnname == 'iseditprice '">
                    {{scope.column.data.iseditprice == '1' ? $t('是'):$t('否') }}
                  </p>
                  <p v-else>{{$t(scope.column.data[scope.column.columnname])}}</p>
                </template>
                <template v-slot:opreation="scope">
                  <el-button type="text" disabled>{{$t('删 除')}}</el-button>
                </template>
              </tableNewLayout>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
    </div>
    <div class="fixed__btn__panel">
      <el-button size="small" @click="dialogFormVisible = false" class="normal-btn-width">{{$t('取 消')}}</el-button>
      <el-button size="small" type="primary" @click="onSubmit" class="normal-btn-width">{{$t('确 定')}}</el-button>
    </div>
  </el-drawer>
</div>
</template>

<script>
import {mapGetters} from 'vuex'
import selectMenber from '@/components/selectMenber/index.vue'
import areaList from "@/HManagement/marketing2/saler/area/modules/areaList";
import addSalers from "@/HManagement/department/staff/list/modules/addSalers";
export default {
  components:{
    selectMenber,
    areaList,
    addSalers
  },
  computed:{
    ...mapGetters({
      sys_options:'sys_options'
    })
  },
  data () {
    return {
      dialogFormVisible:false,
      visible:false,
      rules:{
        hrcode: [
          { required: true, message: this.$t('请输入员工编码'), trigger: 'blur' },
        ],
        name: [
          { required: true, message: this.$t('请输入员工姓名'), trigger: 'blur' },
        ],
        depname: [
          { required: true, message: this.$t('请选择部门'), trigger: 'change' },
        ],
        tradefield: [
          { required: true, message: this.$t('请选择报备领域'), trigger: 'blur,change' },
        ],
        phonenumber: [
          { required: true, message: this.$t('请输入员工电话'), trigger: 'blur' },
          { pattern:/^1[3-9]\d{9}$/, message: this.$t('请输入正确手机号码'),trigger: 'blur' }
        ],
        email:[
          { pattern:/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: this.$t('请输入正确邮箱'),trigger: 'blur' }
        ],
        discountrate: [
        { required: true, message: this.$t('请输入最低授权折扣'), trigger: 'blur' },
        { pattern:/^[0-9]+\.{0,1}[0-9]{0,2}$/,message: this.$t('只能输入数值'),trigger: 'blur'},
        ],
      },
      form:{
        "hrid":0,
        "hrcode":"",
        "name":"",
        "sex":0,
        "phonenumber":"",
        "officetelephone":"",
        "idcard":"",
        "email":"",
        "birthday":"",
        "remarks":"",
        "departmentid":"",
        "isleader":"",
        "position":"",
        "reporthrid":"",
        "userid":"0",
        "statue":0,
        'isuppictured':'0',
        'reporthrname':'',
        'issalehr':'0',
        "salearea": []
      },
      value:[],
      deplist:[],
      pointValue:'',
      issalehr:'',
      tradefields:[],
      tablecols:[],
      list:[],
      salerList:[]
    }
  },
  methods:{
    async query_hrMain () {
      const res = await this.$api.requested({
        "classname": "webmanage.hr.hr",
        "method": "query_hrMain",
        "content": {
            "hrid":this.$route.query.id
        }
      })
      this.form = Object.assign({},this.form, res.data)
      /*this.form.discountrate = Math.round((this.form.discountrate*100)*100)/100*/
      this.issalehr = this.form.issalehr
      this.salerList = res.data.salearea.map(item=>{
        return {
          "name":this.form.name,
          "areaname":item.areaname,
          "discountrate":Math.round((item.discountrate * 100)*100)/100,
          "iseditprice":item.iseditprice,
          "sa_saleareaid":item.sa_saleareaid
        }
      })
    },
    areaLists(val){
      if (this.form.areaname == ''){
        this.form.areaname = val[0].areaname
        this.form.sa_saleareaid = val[0].sa_saleareaid
        this.form.discountrate = ''
      }

    },
    async department () {
      const res = await this.$api.requested({
        "classname": "webmanage.department.department",
        "method": "querydepartment",
        "content": {
        }
      })
      // 数据格式转换成elementui-tree所需的格式
      this.deplist = this.createMenu(res.data)
    },
    createMenu (array) {
      var that = this
      let arr = []
      function convertToElementTree(node) {
        // 新节点
        var elNode = {
          label: node["depname"],
          parentid:node['parentid'],
          departmentid:node["departmentid"],
          value:node["departmentid"],
          remarks:node["remarks"],
          isused:node["isused"],
          changedate:node['changedate'],
          changeby:node['changeby'],
          createdate:node['createdate'],
          createby:node['createby'],
          depno:node['depno'],
          children: []
        }

        if (node.subdep && node.subdep.length > 0) {
          // 如果存在子节点
          for (var index = 0; index < node.subdep.length; index++) {
          // 遍历子节点, 把每个子节点看做一颗独立的树, 传入递归构造子树, 并把结果放回到新node的children中
          elNode.children.push(convertToElementTree(node.subdep[index]));
          }
        }
        return elNode;
      }
      array.forEach((element) => {
        arr.push(convertToElementTree(element))
      });
      return arr
    },
    onShow () {
      this.list = []
      this.salerList = []
      this.query_hrMain()
      this.department()
      this.$store.dispatch('optiontypeselect','tradefield').then(res=>{
        this.tradefields = res.data
      })
      this.$store.dispatch('optiontypeselect','sex')
      this.dialogFormVisible = true
    },
    selectDep  (data) {
      let obj = {
        depname:data.label,
        departmentid:data.departmentid
      }
      this.form = Object.assign({},this.form,obj)
      this.showTree = !this.showTree
      this.issalehr = this.form.issalehr
    },
    onSubmit () {
      this.$refs['form'].validate(async (valid) => {
        if (!valid)  return false;
        /*this.form.discountrate = (this.form.discountrate /100).toFixed(4)*/
        this.form.salearea = this.salerList.map(item=>{
          return {
            "sa_saleareaid": item.sa_saleareaid,
            "discountrate": (item.discountrate/100).toFixed(4),
            "iseditprice": item.iseditprice
          }
        })
        const res = await this.$api.requested({
          "classname": "webmanage.hr.hr",
          "method": "insertormodify_hr",
          "content": this.form
        })
        if (res.code === 0)  return this.$notify({
            title: this.$t('失败'),
            message: res.msg,
            type: 'error'
          });

          this.$notify({
            title: this.$t('成功'),
            message: this.$t('编辑成功'),
            type: 'success'
          });

          this.dialogFormVisible = false
          this.$emit('onSuccess')
      });
    },
    // 监听汇报对象选择
    selectMenber (data) {
      this.form.reporthrid = data.hrid
    },
    nodeClick(val){
      this.pointValue = val.departmentid
      this.visible = false
      this.selectDep(val)
    },
    selectArea(val){
      this.form.areaname = val.label
      this.form.sa_saleareaid = val.sa_saleareaid
    },
    discountrateChange(val){
      if (val < 0){
        this.form.discountrate = 1
      }else if(val > 100){
        this.form.discountrate = 100
      }else {
        this.form.discountrate = Math.round(val * 100)/100
      }
    },
    salerInfo(val){
      console.log(val,'创建的任务')
      /* this.list.push(newList)*/
      this.list = this.salerList
      /*this.list.splice(-1,0,val)*/
      this.list.push(val)
      console.log(this.list,'list表格数据')
      this.salerList = []
      this.salerList = this.list.map(item=>{
        console.log(item.iseditprice)
        return {
          "name":this.form.name,
          "areaname":item.areaname,
          "discountrate":item.discountrate,
          "iseditprice":item.iseditprice,
          "sa_saleareaid":item.sa_saleareaid
        }
      })
      console.log(this.salerList,'salerList')
    }
  },
  created() {
    this.tablecols = this.tool.tabelCol(this.$route.name).salerTable.tablecols
  }
}

</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  background: none;
}
</style>
<style scoped>
.mb-30{
  margin-bottom:12px
}
</style>
