<template>
  <div>
    <div class="container normal-panel normal-margin">
      <el-button type="warning" size="small" icon="el-icon-s-claim" @click="onSubmit">保 存</el-button>
    </div>
    <div class="container normal-panel normal-margin">
      <p class="normal-title normal-margin">经销商信息</p>
      <el-row :gutter="20">
        <el-form :model="form" :rules="rule" ref="form" size="small" status-icon label-position="left" label-width="120px" class="demo-ruleForm">
          <el-col :span="8">
            <el-form-item label="经销商编号" prop="agentnum">
              <el-input class="width-240" type="text" v-model="form.agentnum" placeholder="请输入" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="经销商名称" prop="agentname">
              <el-input class="width-240" type="text" v-model="form.agentname" placeholder="请输入" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="省市县" prop="value">
              <el-cascader
                class="width-240"
                v-model="form.value"
                :options="arealist"
                @change="cascaderChange">
              </el-cascader>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input type="textarea" class="width-240" v-model="form.address"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="contact">
              <el-input class="width-240" type="text" v-model="form.contact" placeholder="请输入" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="联系人手机号" prop="phonenumber">
              <el-input class="width-240" type="number" v-model="form.phonenumber" placeholder="请输入" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="所属营销区域">
              <el-popover
                placement="bottom"
                width="400"
                trigger="click">
                <arealist @onClick="onClick" :noDefaultData="true"></arealist>
                <el-input  slot="reference" class="width-240" readonly v-model="form.areaname" suffix-icon="el-icon-arrow-down"></el-input>
              </el-popover>
            </el-form-item>
            <el-form-item label="合作开始时间" prop="signdate">
              <el-date-picker
                class="width-240"
                v-model="form.signdate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经销商类别" prop="agenttypemx">
              <el-select class="width-240" v-model="form.agenttypemx" placeholder="请选择">
                <el-option
                  v-for="item in agent_type"
                  :key="item.value"
                  :label="item.value"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="伙伴类型" prop="partnertype">
              <el-input class="width-240" type="text" readonly v-model="form.agenttype" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="上级经销商" prop="parentid">
              <!-- <el-input class="width-240" v-model.number="form.age"></el-input> -->
              <selectAgent ref="agent" class="width-240" @selectAgent="selectAgent"></selectAgent>
            </el-form-item>
            <el-form-item label="经销商等级" prop="grade">
              <el-select class="width-240" v-model="form.grade" placeholder="请选择">
                <el-option
                  v-for="item in agent_level"
                  :key="item.value"
                  :label="item.value"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>
    <div  class="my-tabs" style="padding:0 16px">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="经销商团队" name="first"></el-tab-pane>
        <!-- <el-tab-pane label="业绩目标" name="second"></el-tab-pane> -->
        <el-tab-pane label="代理区域" name="area"></el-tab-pane>
      </el-tabs>
    </div>
    <div class="container normal-panel">
      <template v-if="activeName=='first'">
        <el-button class="normal-margin" type="primary" size="small" @click="createAgentMainUser">创建经销商主账号</el-button>
        <tableLayout :layout="tablecols" :data="form.hrs" :custom="false" height="300px"></tableLayout>
      </template>
      <template v-if="activeName=='area'">
        <div class="area-header">
          <!-- <Search /> -->
          <add-agent-btn :arealist="arealist" @areaAddSuccess="areaAddSuccess"></add-agent-btn>
        </div>
        <tableLayout :layout="tablecols2" :data="agentAreaList" :custom="true" height="300px">
          <template v-slot:customcol="scope">
              <span>{{scope.column.data[scope.column.columnname] && scope.column.columnname != 'operation'?scope.column.data[scope.column.columnname]:'--'}}</span>
          </template>
          <template v-slot:opreation="scope">
            <div class="handle">
              <delAgentArea :data="scope.data" type="text" @onAgentSuccess="onAgentSuccess" v-if="tool.checkAuth($route.name,'agent_area_delete')" />
              <editAgentArea :arealist="arealist" :areaData="scope.data" @areaAddSuccess="areaAddSuccess" v-if="tool.checkAuth($route.name,'agent_area_edit')" />
            </div>
          </template>
        </tableLayout>
      </template>
    </div>
    
    <div>
    </div>
  </div>
</template>

<script>
import selectAgent from '../../../../components/selectAgent/index.vue'
import arealist from '../../area/list.vue'
import Search from '@/components/search/index.vue'
import addAgentBtn from './add_agent_btn'
import delAgentArea from './del_agent_area'
import editAgentArea from './edit_agent_area'
export default {
  components:{
    selectAgent,
    arealist,
    Search,
    addAgentBtn,
    delAgentArea,
    editAgentArea
  },
  data () {
    return {
      activeName:'first',
      form:{
        "value":[],
        "sa_agentsid": 0,
        "parentid":"",
        "areaname":'',
        "agentnum":"",
        "agentname":"",
        "address":"",
        "agenttype":"",
        "signdate":"",
        "grade":'',
        "sa_saleareaid":'',
        "contact":"",
        "phonenumber":"",
        "province":"",
        "city":"",
        "county":""
      },
      rule:{
        agentnum:[{ required: true, message: '请输入经销商编号', trigger: 'blur' }],
        agentname:[{ required: true, message: '请输入经销商名称', trigger: 'blur' }],
        value:[
          { required: true, message: '请选择省市县', trigger: 'blur' },
          { required: true, message: '请选择省市县', trigger: 'change' }
        ],
        contact:[{ required: true, message: '请输入联系人', trigger: 'blur' }],
        phonenumber:[{ required: true, message: '请输入联系人手机号', trigger: 'blur' }, { pattern:/^1[3-9]\d{9}$/, message: '请输入正确手机号码',trigger: 'blur' }],
        sa_saleareaname:[{ required: true, message: '请输入营销区域', trigger: 'blur' }],
        signdate:[{required: true, message: '请选择时间', trigger: 'change' }],
        agenttype:[{ required: true, message: '请选择经销商类别', trigger: 'change' }],
        grade:[{ required: true, message: '请选择经销商等级', trigger: 'change' }],
      },
      arealist:[],
      agent_type:[],
      agent_level:[],
      tablecols:[],
      tablecols2:[],
      agentAreaList:[]
    }
  },
  methods:{
    async query_agentMain () {
      const res = await this.$api.requested({
        "classname": "webmanage.sale.agents.agents",
        "method": "query_agentMain",
        "content": {
            "sa_agentsid": this.$route.query.id
        }
      })
      let arr = ['province','city','county']
      res.data.value = []
      arr.forEach(e=>{
        res.data[e] !== '' ?res.data.value.push(res.data[e]):''
      })
      this.form = Object.assign({},this.form,res.data)
      this.$refs.agent.value.agentname = res.data.parentagentname      
    },
    async query_arealist() {
      const res = await this.$api.requested({
        "classname": "system.tools",
        "method": "query_arealist",
        "content": {
        }
      })
      this.arealist = this.tool.createMenu(res.data)
    },
    async query_agent_areaList() {
      let res = await this.$api.requested({
        "accesstoken": "9c3a065cb578fc27cabd392bcad7eec1",
        "classname": "webmanage.sale.agentscope.agentscope",
        "method": "query_areascope",
        "content": {
            "nocache": true,
            "sa_agentsid":this.$route.query.id
        }
      })
      this.agentAreaList = res.data
      console.log(this.agentAreaList);
      
    },
    cascaderChange (val) {
      if (val.length === 1) 
        return this.form = Object.assign({},this.form,{province:val[0],city:'',county:''})

      this.form = Object.assign({},this.form,{province:val[0],city:val[1],county:val[2]})
      
    },
    async query_sysoptions () {
      const res = await this.$store.dispatch('optiontypeselect','agentgrade')
      this.agent_level = res.data
      const res1 = await this.$store.dispatch('optiontypeselect','agenttypemx')
      this.agent_type = res1.data
    },
    areaAddSuccess(data) {
      console.log(data);
      
      this.agentAreaList = data
    },
    selectAgent (data) {
      this.form.parentid = data.sa_agentsid
    },
    onClick (data) {
      this.form.sa_saleareaid = data.sa_saleareaid
      this.form.areaname = data.label
    },
    async createAgentMainUser () {
      const res = await this.$api.requested({
        "classname": "webmanage.sale.agents.agents",
        "method": "createAgentMainUser",
        "content": {
            "sa_agentsid":this.form.sa_agentsid
        }
      })
      this.tool.showMessage(res)
      this.query_agentMain()
    },
    onSubmit () {
      this.$refs['form'].validate(async (valid) => {
        if (!valid) return false
        const res = await this.$api.requested({
          "classname": "webmanage.sale.agents.agents",
          "method": "insertormodify_agent",
          "content": this.form
        })
        this.tool.showMessage(res)
        res.code === 1?this.$router.replace({path:'/agent_detail',query:{id:this.form.sa_agentsid}}):''
      });
    },
    onAgentSuccess() {
      this.query_agent_areaList()      
    }
  },
  created () {
    this.query_agent_areaList()
    // 获取表结构
    this.tablecols = this.tool.tabelCol(this.$route.name)['agentGrouptable'].tablecols
    this.tablecols2 = this.tool.tabelCol(this.$route.name)['agentAreaTable'].tablecols
    // 验证权限
    console.log(this.tool.checkAuth(this.$route.name,'agent_update'))
    this.tool.checkAuth(this.$route.name,'agent_update')?'':this.$router.go(-1)
  },
  mounted () {
    this.query_arealist()
    this.query_sysoptions()
    this.query_agentMain()
  }
}

</script>
<style>
</style>
<style scoped>
.width-240{
  width: 240px;
}
.area-header {
  display: flex;
  justify-content: space-between;
}
.handle {
  display: flex;
  justify-content: space-evenly;
}
</style>