<template>
  <div>
    <el-button type="primary" size="small" @click="onShow">新 建</el-button>
    <el-drawer title="创建经销商" direction="rtl" size="900px" append-to-body :visible.sync="dialogVisible" @close="onClose" :show-close="false">
      <div class="drawer__panel">
      <el-row :gutter="20">
        <el-form :model="form" ref="form" :rules="rules" :status-icon="false"	 size="small" label-position="right" label-width="120px" 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">
              <enterprise ref="ent" @rowClick="chooseEnterprise" type="3"></enterprise>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省市县:">
<!--              <p class="enterpriseText">{{enterprise.province?enterprise.province:''}}</p>-->
              <el-input v-model="enterprise.province" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人:">
              <el-input v-model="enterprise.contact" disabled></el-input>
<!--              <p class="enterpriseText">{{enterprise.contact?enterprise.contact:''}}</p>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式:">
              <el-input v-model="enterprise.phonenumber" disabled></el-input>
<!--              <p class="enterpriseText">{{enterprise.phonenumber?enterprise.phonenumber:''}}</p>-->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址:">
              <el-input v-model="enterprise.address" disabled></el-input>
<!--              <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="erp编号:" prop="erpagentnum">
              <el-input v-model="form.erpagentnum" placeholder="输入erp编号"></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="可退货天数" prop="limitreturnday">
              <el-input v-model.number="form.limitreturnday" placeholder="请输入订单可退货天数"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="上级经销商:">
            <selectAgent ref="agent" @selectAgent="selectAgent" :title="title"></selectAgent>
          </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业等级">
              <el-select size="small" 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">
                  <span style="float: left">{{ item.value }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">{{ item.remarks?item.remarks:'暂无描述' }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="height:51px">
            <el-form-item label="开票节点" prop="invoicingpoint">
              <el-radio-group v-model="form.invoicingpoint">
                <el-radio :label="1">订单审核</el-radio>
                <el-radio :label="2">发货</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否服务经销商:" prop="isservice">
              <el-checkbox v-model="form.isservice" :true-label="1" :false-label="0"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否授权所有营销类别:" prop="saleclassauth" label-width="160px">
              <el-checkbox v-model="form.saleclassauth" :true-label="0" :false-label="1"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="是否免运费">
              <el-radio-group v-model="radio" @change="radioChange">
                <el-radio :label="-1">不免费运费</el-radio>
                <el-radio :label="0">免运费</el-radio>
                <el-radio :label="1">其他</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="radio === 1">
            <el-form-item label="免运费额度" prop="freefreightamount">
              <el-input v-model.number="form.freefreightamount" placeholder="请输入免运费额度"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      </div>
      <div class="fixed__btn__panel">
        <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-drawer>
  </div>
</template>

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

selectAgent
export default {
  data () {
    return {
      radio:-1,
      title:'选择上级经销商',
      rules: {
        enterprisename: [
          { required: true, message: '请输入企业名称', trigger: 'blur' },
        ],
        agentnum: [
          { required: true, message: '请输入经销商编号', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '请选择经销商类型', trigger: 'change' },
        ],
        erpagentnum: [
          { required: true, message: '请输入erp经销商编号', trigger: 'change' },
        ],
      },
      dialogVisible:false,
      visible:false,
      form:{
        "enterprisename": "",
        "sa_agentsid": '',
        "parentid": "",
        "agentnum": "",
        "signdate": "",
        "grade": "",
        "sys_enterpriseid": '',
        "sa_saleareaids": [

        ],
        "type": "",
        "erpagentnum": "",
        "isservice": 1, //是否服务商，0或1
        "limitreturnday": "", //订单可退货天数
        "freefreightamount": "", //免运费额度
        "latitude": "", //纬度
        "longitude": "", //经度
        "invoicingpoint": 1, //开票节点（1:订单审核：2:发货）
        "saleclassauth": 1, //是否需要经营授权,默认1
        "grade":''
      },
      ENlist:[],
      agent_level:[],
      arealist:[],
      agent_type:[],
      enterprise:{},
      timer:0
    }
  },
  components:{
    enterprise,
    selectAgent
  },
  methods:{
    onShow () {
      this.dialogVisible = true
      this.query_sysoptions()
      this.query_arealist()
    },
    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
          })
      })
    },
    radioChange (val) {
      switch (val) {
        case -1:
          this.form.freefreightamount = -1
          break;
        case 0:
          this.form.freefreightamount = 0
          break;
        default:
          this.form.freefreightamount = ''
          break;
      }
    },
    onChange () {
      this.visible = true
      this.debounce(this.queryEnterpriseArchives,500)()
    },
    onCascaderChange (value) {
      this.form.sa_saleareaid = value.at(-1)
    },
    debounce (fn, wait) {
      return function () {
        if (this.timer !== null) clearTimeout(this.timer)
        this.timer = setTimeout(fn, wait)
      }
    },
    chooseEnterprise (item) {
      this.visible = false
      this.form.enterprisename = item.enterprisename
      this.form.sys_enterpriseid = item.sys_enterpriseid
      item.province = `${item.province}-${item.city}-${item.county}`
      this.enterprise = item
    },
    selectAgent (data) {
      this.form.parentid = data.sa_agentsid
    },
    onClose () {
      this.$refs['ent'].form = {}
      this.form = {
        "enterprisename": "",
        "sa_agentsid": '',
        "parentid": "",
        "agentnum": "",
        "signdate": "",
        "grade": "",
        "sys_enterpriseid": '',
        "sa_saleareaids": [

        ],
        "type": "",
        "erpagentnum": "",
        "isservice": 1, //是否服务商，0或1
        "limitreturnday": "", //订单可退货天数
        "freefreightamount": "", //免运费额度
        "latitude": "", //纬度
        "longitude": "", //经度
        "invoicingpoint": 1, //开票节点（1:订单审核：2:发货）
        "saleclassauth": 1, //是否需要经营授权,默认1
        "grade":''
      },
      this.enterprise = {}
    }
  },
  
}

</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>