<template>
  <div class="eibs-tab">
    <div style="text-align: left">
      <c-button size="small" type="primary" v-if="showInsertBtn" ref="adrInsertBtn" @click="adrAdd()" :disabled="type=='info'||(type=='edit' &&(   (zhFlg=='Y'&&cwFlg=='Y')||(zhFlg!='Y'&&cwFlg=='Y'&&zFlg!='Y'&&xFlg!='Y')   )) "> 新增 </c-button>
    </div>
    <el-form-item label="" label-width="0" prop="adrInfo">
      <c-table :columnsConfig="columns" :list="adrList">
        <c-table-column fixed="right" prop="op" label="操作" width="200px">
          <template slot-scope="{ scope }">
            <button class="el-button el-button--default el-button--small" style="margin-left: 0" size="small"
              :disabled="false" ref="adrDisplayBtn" @click.prevent="adrInfo(scope.$index, scope.row)">
              <span>详情</span>
            </button>
            <c-button style="margin-left: 5px" size="small" type="primary" :disabled="isPageInfo || (cwFlg!='Y' && !scope.row.hasOpAuth)||(cwFlg=='Y' && (   (scope.row.usg == '主地址' && zFlg != 'Y') ||  (scope.row.usg != '主地址' && zFlg != 'Y' && !xBchkeycodeList.includes(scope.row.bchkeycode))  ))" v-if="showUpdateBtn" ref="adrUpdateBtn" @click="adrEdit(scope.$index, scope.row)">
              修改
            </c-button>
            <c-button style="margin-left: 5px" size="small" type="primary" :disabled="isPageInfo || (cwFlg!='Y' && !scope.row.hasOpAuth)||(cwFlg=='Y' && (   (scope.row.usg == '主地址' && zFlg != 'Y') ||  (scope.row.usg != '主地址' && zFlg != 'Y' && !xBchkeycodeList.includes(scope.row.bchkeycode))  ))" v-if="showDeleteBtn" ref="adrDeleteBtn" @click="adrDelete(scope.$index, scope.row)">
              删除
            </c-button>
          </template>
        </c-table-column>
      </c-table>
    </el-form-item>

    <el-dialog
      :title="
        '地址信息:' +
        (operate === 'details' ? '详情' : operate === 'edit' ? '修改' : '新增')
      "
      :visible.sync="adrDialog"
      top="10vh"
      width="80%"
      :destroy-on-close="true"
      :before-close="handleClose"
    >
      <m-adr-info ref="adr" :adr="adr" :model="model" :operate="operate" @changeObjkey="changeObjkey" :bchlist="bchlist"></m-adr-info>
      <span slot="footer" class="dialog-footer">
        <button v-if="operate !== 'details'"
          class="el-button el-button--default el-button--small"
          style="margin-left: 0"
          size="small"
          :disabled="false"
          @click.prevent="cancel"
        >
          <span>取 消</span>
        </button>
        <c-button type="primary" @click="cancel" v-if="operate === 'details'"
          >返 回</c-button
        >
        <c-button type="primary" @click="editAdr" v-if="operate === 'edit'"
          >保 存</c-button
        >
        <c-button type="primary" @click="saveAdr" v-if="operate === 'add'"
          >保 存</c-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Adrn from "./Adrn.js";
import AdrInfo from "./AdrInfo.vue";
import {getBchlist,getBranchlist1} from "~/service/manage/ptyn.js";
//import { getBchlist, getBranchlist1 } from "~/service/manage/pty.js";
import Api from "~/service/Api"


import {
  queryAdrlist,
  queryDetailById,
  add,
  edit,
  deleteById,
} from "~/service/manage/adr.js";

export default {
  name: "AdrList",
  components: {
    "m-adr-info": AdrInfo,
  },
  inject: ["root"],
  props: ["model","type"],
  data() {
    return {
      adrDialog: false,
      adr: null,
      adrList: [],
      operate: "",
      operateIdx: 0,
      bchlist: [],
      bchlistold: [],
      branchlist: [],
      columns: [
        { label: "主地址", prop: "usg", width: "auto" },
        { label: "地址编号", prop: "extkey", width: "auto" },
        { label: "英文名称", prop: "nam", width: "auto" },
        { label: "英文地址", prop: "enadr", width: "auto" },
        { label: "中文地址", prop: "cnadr", width: "auto" },
        { label: "所属机构", prop: "branchcode", width: "auto" },
        { label: "机构名称", prop: "bchname", width: "auto" },
      ],
      showInsertBtn:true,
      showUpdateBtn:true,
      showDeleteBtn:true,
      xBchkeycodeList:[],
      zFlg:"",
      xFlg:"",
      zhFlg:"",
      cwFlg:"",

      bchAuthMod:{
        cod_:"",
        msg_:"",
        zFlg:"N",
        zMsg:"",
        zBchList:[],
        zBchkeyList:[],
        zBranchList:[],

        xFlg:"N",
        xMsg:"",
        xBchList:[],
        xBchkeyList:[],
        xBranchList:[],
      },
      
    };
  },
  watch: {
    '$store.state.UserContext.currentOrg': {
      handler(newVal) {
        this.getBchlist1();
      }
    },
  },
  created() {
      if (this.root.bchAuthMod !=null && this.root.bchAuthMod.xBchkeyList != null) {
        for (let i of this.root.bchAuthMod.xBchkeyList){
          this.xBchkeycodeList.push([i.branch])
        }
      }
  },
  mounted(){
    this.getHiddenButtonVue();
    this.zFlg=this.$route.query.zFlg;
    this.xFlg=this.$route.query.xFlg;
    this.zhFlg=this.$route.query.zhFlg;
    this.cwFlg=this.$route.query.cwFlg;
	},
  computed: {
    isPageInfo() {
      if (this.type=="info") {
        return true
      }else{
        return false
      }
    },
  },
  methods: {
    init() {
      const ptyinr = this.$route.query.inr;
      queryAdrlist({"ptyinr": ptyinr}).then((res)=> {
        if (res.respCode == "AAAAAA") {
        //   this.$set(this, "model", res.data)
        //   this.adrInfo = res.data
          this.$set(this, "adrList", res.data)
          res.data.map((item) => {
            if(item.usg == "主地址") {
              this.isselected = item.inr
            }
          })

          this.bchAuthMod=JSON.parse(localStorage.getItem("bchAuthMod"))
        } else {
          this.$notify.error("客户不存在")
        }
      });
      this.getBchlist1();
    },
    getHiddenButtonVue(){
      this.$buttonControlService.hiddenBtnList()
      .then((res)=>{
        for(let i = 0;i<res.length;i++){
          if(res[i].ITEMID === 'adrUpdateBtn'){
            this.showUpdateBtn = false;
          }
          if(res[i].ITEMID === 'adrDeleteBtn'){
            this.showDeleteBtn = false;
          }  
          if(res[i].ITEMID === 'adrInsertBtn'){
            this.showInsertBtn = false;
          }
          // if(res[i].ITEMID === 'actUpdateBtn'){
          //   this.$refs.actChild.showUpdateBtn = false;
          // }
          // if(res[i].ITEMID === 'actDeleteBtn'){
          //   this.$refs.actChild.showDeleteBtn = false;
          // }  
          // if(res[i].ITEMID === 'actInsertBtn'){
          //   this.$refs.actChild.showInsertBtn = false;
          // }
          // if(res[i].ITEMID === 'signInsertBtn'){
          //   this.$refs.signChild.showInsertBtn = false;
          // }
          // if(res[i].ITEMID === 'signUpdateBtn'){
          //   this.$refs.signChild.showUpdateBtn = false;
          // }
          // if(res[i].ITEMID === 'ptmNInsertBtn'){
          //   this.$refs.ptmChild.isShowAddBtn = false;
          // }
          // if(res[i].ITEMID === 'ptmNUpdateBtn'){
          //   this.$refs.ptmChild.isShowUpdBtn = false;
          // }
          // if(res[i].ITEMID === 'ptmNDeleteBtn'){
          //   this.$refs.ptmChild.isShowDelBtn = false;
          // }
        }
      })
    },
    getBchlist1() {
      getBchlist().then((res) => {
        if (res.respCode == "AAAAAA") {
          this.bchlist = res.data
          this.bchlistold=this.bchlist
        }
      })
    },
    onSearch() {
      const ptyinr = this.$route.query.inr;
      queryAdrlist({"ptyinr": ptyinr}).then((res)=> {
        if (res.respCode == "AAAAAA") {
          this.$set(this, "adrList", res.data)
        }});
    },
    /**
     * 详情
     */
    adrInfo(index, row) {
      queryDetailById((row)).then((res) => {
            if (res.respCode == "AAAAAA") {
              this.adr = res.data
              this.adr.ptyextkey = this.model.extkey
              this.adr.ptynam = this.model.nam
              this.adr.ptytyp = this.model.ptytyp

              if (this.$route.query.cwFlg=="Y"){
                console.log("--------------------",this.bchlist)

                let a=1 //不存在
                for (let i of this.bchlist){
                  if (i.branch == this.adr.bchkeybch.branch){
                    a=2 //已存在
                    break
                  }
                }

                if (a == 1){
                  this.bchlist.push(this.adr.bchkeybch)
                }

                this.branchlist=[]
                this.branchlist.push(this.adr.branchbch)
                console.log("333333333333")
                console.log("--------------------",a)

              }

            }
        });
      this.operate = "details";
      this.operateIdx = index;
      this.adrDialog = true;
    },
    /**
     * 新增
     */
    adrAdd() {
      var adr = new Adrn().data;
      adr.ptyextkey = this.model.extkey
      adr.ptynam = this.model.nam
      adr.usg="MAB";
      adr.ptytyp = this.model.ptytyp
      console.log("adrAdd--",this.mode,adr)
      this.$set(this, "adr", adr)
      this.operate = "add";

      if (this.$route.query.cwFlg=="Y"){
      //主协办机构
      if ((this.bchAuthMod.zBchList == null ||this.bchAuthMod.zBchList.length<=0) && (this.bchAuthMod.xBchList == null ||this.bchAuthMod.xBchList.length<=0)  ){
                   this.$notify.warning({title: '提示:',message: "未获取到客户主协办机构!",dangerouslyUseHTMLString: true }); 
      }
      
      let tmp=[]
      //添加主办记账机构
      for(let i of this.bchAuthMod.zBchkeyList) {
        tmp.push(i)  
      }
      //添加协办记账机构,并和主办机构去重
      for(let i of this.bchAuthMod.xBchkeyList) {
        let flg =false
        //去重
        for(let j of tmp) {
          if (j.branch==i.branch){
            flg =true
            break
          }
        }
        if (!flg){
          tmp.push(i) 
        }  
      }
      
      console.log("1----this.bchlist",this.bchlist)
      //0930返回的是记账机构A B C, 原来归属机构的记账机构是A,则只可以选择A
      let tmp1=[]
      for(let i of tmp) {
        for(let j of this.bchlistold) {
          if (j.branch==i.branch){
            tmp1.push(i)
          }
        }  
      }
         
      this.bchlist=tmp1
      console.log("2----this.bchlist",this.bchlist)
      }

      this.adrDialog = true;
    },
    /**
     * 修改
     */
    adrEdit(index, row) {
      queryDetailById((row)).then((res) => {
            if (res.respCode == "AAAAAA") {
                this.adr = res.data
                this.adr.ptyextkey = this.model.extkey
                this.adr.ptynam = this.model.nam
                this.adr.ptytyp = this.model.ptytyp

                if (this.$route.query.cwFlg=="Y"){
                getBranchlist1({"bchkeycode": this.adr.bchkeycode}).then((res) => {
                  if (res.respCode == SUCCESS) {
                    this.branchlist = res.data
                  }
                })
                }


                if (this.$route.query.cwFlg=="Y"){
              //主协办机构
                if ((this.bchAuthMod.zBchList == null ||this.bchAuthMod.zBchList.length<=0) && (this.bchAuthMod.xBchList == null ||this.bchAuthMod.xBchList.length<=0) ){
                         this.$notify.warning({title: '提示:',message: "未获取到客户主协办机构!",dangerouslyUseHTMLString: true }); 
                }
                let tmp=[]
                for(let i of this.bchAuthMod.zBchkeyList) {
                  tmp.push(i)  
                }
                for(let i of this.bchAuthMod.xBchkeyList) {
                  let flg =false
                  for(let j of tmp) {
                    if (j.branch==i.branch){
                      flg =true
                      break
                    }
                  }
                  if (!flg){
                    tmp.push(i) 
                  }  
                }


                console.log("1----this.bchlist",this.bchlist)
                let tmp1=[]
                for(let i of tmp) {
                  for(let j of this.bchlist) {
                    if (j.branch==i.branch){
                      tmp1.push(i)
                    }
                  }  
                }
                

                this.bchlist=tmp1


                let a=1 //不存在
                for (let i of this.bchlist){
                  if (i.branch == this.adr.bchkeybch.branch){
                    a=2 //已存在
                    break
                  }
                }

                if (a == 1){
                  this.bchlist.push(this.adr.bchkeybch)
                }
                console.log("2----this.bchlist",this.bchlist)

            }

            }
        });
      this.operate = "edit";
      this.operateIdx = index;

      

      this.adrDialog = true;
    },
    /**
     * 删除
     */
    adrDelete(index, row) {
      this.$confirm("是否真的删除?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then((res) => {
        deleteById(row).then((res) => {
          if (res.respCode == "AAAAAA") {
            this.$notify.success("删除成功!");
            this.onSearch()
          } else {
            this.$notify.error("删除失败!");
          }
        });
      });
    },
    cancel() {
      this.handleClose();
    },
    changeObjkey (val) {
      this.$set(this.adr, 'ptaextkey', val)
    },
    editAdr() {
      this.$refs.adr.$refs.modelForm.validate((validated) => {
        if (validated) {
          edit(this.adr)
            .then((res) => {
              if (res.respCode == "AAAAAA") {
                this.$notify.success("修改地址信息成功!");
                this.handleClose();
                this.onSearch();
              }
            })
            .catch((error) => {
              this.$notify.error("修改地址信息失败!");
            });
        } else {
          this.$notify.error({
            title: '失败',
            message: '请检查必输项!'
          });
        }
      });
    },
    /**
     * Adr新增有2种情况
     * 1. pty的新增界面下,此时pty的inr为空,adr需要在pty插入之后,才能执行新增,
     *    所以我们在这里不能直接调用新增接口,将adr添加到ptaList中,随着这个pty一起传入接口。
     * 2. pty的修改界面下,可直接新增 ;
     */
    saveAdr() {
      // for (const key in this.adr) {
      //   if (Object.hasOwnProperty.call(this.adr, key)) {
      //     const v = this.adr[key];
      //     if (typeof v === 'string' && v === '') {
      //       this.adr[key] = " "
      //     }
      //   }
      // }
      if (this.root.type === "add") {
        console.log("this.adr1", this.adr)
        this.model.adrInfo.push(this.adr);
        this.handleClose();
      } else {
        console.log("this.adr2", this.adr)
        this.$refs.adr.$refs.modelForm.validate((validated) => {
          if (validated) {
            this.adr.ptyinr = this.model.inr;
            add(this.adr)
              .then((res) => {
                if (res.respCode == SUCCESS) {
                  this.$notify.success("保存地址信息成功!");
                  this.model.adrInfo = res.data.adrInfo;
                  this.handleClose();
                  this.onSearch()
                }
              })
              .catch((error) => {
                this.$notify.error("保存地址信息失败!");
              });
          } else {
          this.$notify.error({
            title: '失败',
            message: '请检查必输项!'
          });
        }
        });
      }
    },
    handleClose(done) {
      this.adrDialog = false;
      if (done && typeof done === "function") {
        done();
      }
    },
  },
};
</script>

<style>
.paginationLable {
  display:none;
}
</style>