<template>
  <div>
    <el-button :type="btnType" size="mini" @click="onShow">编 辑</el-button>
    <el-dialog title="创建经销商" append-to-body :visible.sync="dialogVisible">
      <el-row :gutter="20">
        <el-form :model="form" ref="form" :rules="rules" size="small" label-position="left" label-width="100px" class="demo-form-inline">
          <el-col :span="24">
            <p class="normal-title normal-margin">企业信息</p>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="enterprisename">
              <el-popover
                placement="bottom"
                width="100%"
                v-model="visible">
                <div>
                  <ul class="enterprisePanel">
                    <li v-for="item in ENlist" :key="item.sys_enterpriseid" @click="chooseEnterprise(item)">
                      <p>{{item.enterprisename}}</p>
                      <small>{{item.province}}-{{item.city}}-{{item.county}}</small>
                    </li>
                  </ul>
                </div>
                <el-input readonly slot="reference" v-model="form.enterprisename" @focus="queryEnterpriseArchives" @input.native="onChange"  placeholder="输入企业名称" clearable></el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省市县">
              <p class="enterpriseText">{{enterprise.province?enterprise.province:'--'}}</p>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人">
              <p class="enterpriseText">{{enterprise.contact?enterprise.contact:'--'}}</p>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式">
              <p class="enterpriseText">{{enterprise.phonenumber?enterprise.phonenumber:'--'}}</p>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址">
              <p class="enterpriseText">{{enterprise.address?enterprise.address:'--'}}</p>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <p class="normal-title normal-margin">经销商信息</p>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经销商编号" prop="agentnum">
              <el-input v-model="form.agentnum" placeholder="输入经销商编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签约日期">
              <el-date-picker
                style="width:100%"
                v-model="form.signdate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经销商类型" prop="type">
              <el-select style="width:100%" v-model="form.type" 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-col>
          <el-col :span="12">
            <el-form-item label="上级经销商">
              <selectAgent ref="agent" @selectAgent="selectAgent"></selectAgent>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经销商等级">
              <el-select style="width:100%" v-model="form.grade" placeholder="请选择">
                <el-option
                  v-for="item in agent_level"
                  :key="item.value"
                  :label="item.remarks"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营销区域" prop="sa_saleareaids">
              <el-cascader
                style="width:100%"
                v-model="form.sa_saleareaids"
                :options="arealist"
                :props="{
                  value:'sa_saleareaid',
                  label:'areaname',
                  children:'subarea'
                }"
                :show-all-levels="false"
                @change="onCascaderChange">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false" class="normal-btn-width">取 消</el-button>
        <el-button size="small" type="warning" @click="onSubmit" class="normal-btn-width btn-warning">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import selectAgent from '@/components/selectAgent/index.vue'

export default {
  props:['data','btnType'],
  data () {
    return {
      rules: {
        enterprisename: [
          { required: true, message: '请输入企业名称', trigger: ['blur', 'change'] },
        ],
        agentnum: [
          { required: true, message: '请输入经销商编号', trigger: 'blur' },
        ],
        sa_saleareaids: [
          { required: true, message: '请输入经销商编号', trigger: 'change' },
        ],
        type: [
          { required: true, message: '请选择经销商类型', trigger: 'change' },
        ],
      },
      dialogVisible:false,
      visible:false,
      form:{
        "enterprisename":'',
        "sa_agentsid": 0,
        "parentid":"",
        "agentnum":"",
        "signdate":"",
        "grade":'1',
        "sa_saleareaid":null,
        "sys_enterpriseid":null,
        "sa_saleareaids":[]
      },
      ENlist:[],
      agent_level:[],
      arealist:[],
      agent_type:[],
      enterprise:{}
    }
  },
  components:{
    selectAgent
  },
  methods:{
    onShow () {
      this.dialogVisible = true
      this.query_sysoptions()
      this.query_arealist()
      this.queryMain()
    },
    async queryMain() {
      const res = await this.$api.requested({
        "classname": "webmanage.sale.agents.agents",
        "method": "query_agentMain",
        "content": {
          "sa_agentsid": this.data.sa_agentsid
        }
      })
      this.$refs.agent.value.enterprisename = res.data.parent_enterprisename
      res.data.sa_saleareaids?res.data.sa_saleareaids = JSON.parse(res.data.sa_saleareaids):''
      this.form = Object.assign({},this.form,res.data)
      this.enterprise = Object.assign({},this.form,res.data)
    },
    async queryEnterpriseArchives () {
      const res = await this.$api.requested({
        "id": 20220920083901,
        "content": {
          "pageNumber": 1,
          "pageSize": 20,
          "where": {
            "condition": this.form.enterprisename
          }
        }
      })
      this.ENlist = res.data
    },
    async query_arealist (callback) {
      const res = await this.$api.requested({
        "classname": "webmanage.sale.salearea.salearea",
        "method": "query_area",
        "content": {
        }
      })
      this.arealist = this.createList(res.data)
    },
    createList (array) {
      var that = this
      let arr = []
      function convertToElementTree(node) {
        if (node.subarea && node.subarea.length > 0) {
          for (var index = 0; index < node.subarea.length; index++) {
            convertToElementTree(node.subarea[index])
          }
        } else {
          node.subarea = null
        }
        return node;
      }
      array.forEach((element) => {
        arr.push(convertToElementTree(element))
      });
      return arr
    },
    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
    },
    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,()=>{
            this.$emit('onSuccess')
            // this.$refs['form'].resetFields();
            this.dialogVisible = false
          })
      })
    },
    onChange () {
      this.visible = true
      this.debounce(this.queryEnterpriseArchives,1000)()
    },
    onCascaderChange (value) {
      this.form.sa_saleareaid = value.at(-1)
    },
    debounce (fn, wait) {
      let timer = 0
      return function () {
        if (timer !== null) clearTimeout(timer)
        timer = setTimeout(fn, wait)
      }
    },
    chooseEnterprise (item) {
      this.visible = false
      this.form.enterprisename = item.enterprisename
      this.form.enterpriseid = item.enterpriseid

      item.province = `${item.province}-${item.city}-${item.county}`
      this.enterprise = item
    },
    selectAgent (data) {
      this.form.parentid = data.sa_agentsid
    },
   
  },
  
}

</script>
<style>
</style>
<style scoped>
.enterprisePanel {
  max-height: 400px;
  overflow-y: scroll;
}
.enterprisePanel li{
  padding: 10px;
  cursor: pointer;
  line-height: 25px;
}
.enterprisePanel li small{
  color: #999;
}
.enterprisePanel li:hover{
  background: #f1f2f3;
}
.enterpriseText{
  height: 34px;
  line-height: 34px;
  font-weight: 500;
}
</style>