<template>
  <div>
    <div style="display: flex;">
      <div :style="'width:' + (window.pageWidth - 200 - 110 - 25) + 'px;'">
        <el-table :data="contactPersonList" border :height="(window.pageHeight < 600 ? 100 : window.pageHeight - 400) / 2"
          size="small" highlight-current-row @row-click="rowClick" ref="contactPersonList">
          <el-table-column prop="displayName" label="姓名" min-width="70" align="center" />
          <el-table-column prop="title" label="职务" min-width="70" align="center" />
          <el-table-column prop="remark" label="备注" min-width="150" align="center" />
          <el-table-column prop="creatorName" label="创建者" min-width="70" align="center" />
          <el-table-column prop="creationTime" label="创建时间" min-width="120" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.creationTime">
                {{ moment(scope.row.creationTime).format('yyyy-MM-DD HH:mm:ss') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="lastModifierName" label="修改者" min-width="70" align="center" />
          <el-table-column prop="lastModificationTime" label="修改时间" min-width="120" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.lastModificationTime">
                {{ moment(scope.row.lastModificationTime).format('yyyy-MM-DD HH:mm:ss') }}
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-table :data="contactMethodList" border :height="(window.pageHeight < 600 ? 100 : window.pageHeight - 400) / 2"
          size="small" highlight-current-row ref="contactMethodList">
          <el-table-column prop="contactMethodType" label="类型" width="60" align="center">
            <template slot-scope="scope">
              <div>
                {{ scope.row.contactMethodType === "0" ? "手机" : "邮箱" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="contactMethodValue" label="联系方式" min-width="120" align="center" />
          <el-table-column prop="creatorName" label="创建者" min-width="70" align="center" />
          <el-table-column prop="creationTime" label="创建时间" min-width="120" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.creationTime">
                {{ moment(scope.row.creationTime).format('yyyy-MM-DD HH:mm:ss') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="lastModifierName" label="修改者" min-width="70" align="center" />
          <el-table-column prop="lastModificationTime" label="修改时间" min-width="120" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.lastModificationTime">
                {{ moment(scope.row.lastModificationTime).format('yyyy-MM-DD HH:mm:ss') }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-left: 10px; margin-top: 20px">
        <div v-show="checkPagePriv(pagePriv.privs, '新增联系人')" style="margin-top: 10px">
          <el-button type="primary" @click="btnAdd" class="commonbutton">新增联系人</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '编辑联系人')" style="margin-top: 10px">
          <el-button type="success" @click="btnEdit" class="commonbutton">编辑联系人</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '删除联系人')" style="margin-top: 10px">
          <el-button type="danger" @click="btnDel" class="deleteButton">删除联系人</el-button>
        </div>
      </div>
    </div>
    <!-- 联系人 -->
    <el-dialog :title="`${dataTransOpts.tableS.contact_person.id ? '编辑' : '新增'}联系人`"
      :visible.sync="dialogWin.ContactPersonEdit" width="800px" @close="close_dialogWin_ContactPersonEdit">
      <ContactPersonEdit :refFunc="setData" />
    </el-dialog>
  </div>
</template>
<script>
import moment from "moment";
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { getPagePriv, checkPagePriv, objCopy, deepCopy, arrayExistObj, setData } from "../../utlis/proFunc";
import ContactPersonEdit from '../../components/customerOrg/ContactPersonEdit.vue'
export default {
  components: {
    ContactPersonEdit
  },
  props: ["customerOrgId"],
  data() {
    return {
      pagePriv: {
        routeUrlorPageName: 'customerOrg', //当前页面归属路由或归属页面权限名称
        privs: [] // 页面权限
      },
      curChooseRow: { id: "" }, // 当前选择联系人信息
      contactPersonList: [], // 联系人列表
      contactMethodList: [], // 联系方式列表
    };
  },

  created() {
    //获取用户当前页面的权限
    let userPriv = window.sessionStorage.getItem('userPriv')
    if (userPriv) this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName))
  },

  //挂载完成
  mounted() {
    this.getContactPersonList(this.dataTransOpts.tableS.customer_org.id)
  },

  computed: {
    ...mapState(["window", "customerOrg", "dialogWin", "dataTransOpts"]),
  },

  methods: {
    moment, checkPagePriv,

    //获取联系人列表
    getContactPersonList(customerOrgId) {
      if (!customerOrgId) {
        this.contactPersonList = [];
        this.contactMethodList = []
        return
      }
      getapi(
        `/api/app/contact-person/in-customer-org-id/${customerOrgId}`
      ).then((res) => {
        if (res.code != -1) {
          this.contactPersonList = res.data;
          if (res.data.length > 0) {
            this.getContactMethodList(res.data[0].id);
          } else {
            this.contactMethodList = [];
          }
        }
      });
    },

    //获取联系方式列表
    //api/app/contact-method/in-contact-person-id?ContactPersonId=3a0c08ad-4304-138b-d9e6-a7338739dfc4' \
    getContactMethodList(ContactPersonId) {
      if (!ContactPersonId) {
        this.contactMethodList = []
        return
      }
      getapi("/api/app/contact-method/in-contact-person-id", {
        ContactPersonId,
      }).then((res) => {
        //console.log('res.data',res.data)
        this.contactMethodList = res.data;
      });
    },

    //联系人 相关操作
    btnAdd() {
      //console.log("新增 addContactPerson");
      if (!this.dataTransOpts.tableS.customer_org.id) {
        this.$message.warning({ showClose: true, message: "没有体检单位信息"});
        return;
      }
      this.dataTransOpts.tableS.contact_person.id = ''
      this.dialogWin.ContactPersonEdit = true;
      setTimeout(() => {
        this.dataTransOpts.refresh.contact_person.S++
      }, 10);
    },

    btnEdit() {
      //console.log("编辑 editContactPerson");
      // console.log('this.customerOrgId',this.customerOrgId)
      if (!this.dataTransOpts.tableS.customer_org.id) {
        this.$message.warning({ showClose: true, message: "没有体检单位信息"});
        return;
      } else if (!this.dataTransOpts.tableS.contact_person.id) {
        this.$message.warning({ showClose: true, message: "请先选择要编辑的联系人"});
        return;
      }
      this.dialogWin.ContactPersonEdit = true;
      this.dataTransOpts.refresh.contact_person.S++
    },



    //删除联系人行
    btnDel() {
      //console.log("删除 delContactPerson");
      if (!this.dataTransOpts.tableS.contact_person.id) {
        this.$message.warning({ showClose: true, message: "请先选择要编辑的联系人"});
        return;
      }

      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }).then(() => {
        //console.log('{patientRegisterIds}',{patientRegisterIds})
        return deletapi(`/api/app/contact-person/${this.dataTransOpts.tableS.contact_person.id}`);
      }).then((res) => {
        if (res.code != -1) {
          let lfind = arrayExistObj(this.contactPersonList, 'id', this.dataTransOpts.tableS.contact_person.id)
          if (lfind > -1) this.contactPersonList.splice(lfind, 1)
          this.dataTransOpts.tableS.contact_person.id = "";
          setTimeout(() => {
            this.dataTransOpts.refresh.contact_method.M++
          }, 10);

          console.log("操作成功！");
        }
      }).catch((err) => {
        if (err == "cancel") console.log("已取消删除");
      });
    },

    // 设置 data 对象的值（暂时支持到7级），供子组件调用
    setData(item, v) {      
      setData(this, item, v)
      console.log('父函数 this.curChooseRow,v', this.curChooseRow, item, v)
    },

    //新增或编辑后选中记录
    close_dialogWin_ContactPersonEdit() {
      let personId = this.curChooseRow.id
      if (this.dataTransOpts.tableS.contact_person.id) personId = this.dataTransOpts.tableS.contact_person.id
      console.log('close_dialogWin_ContactPersonEdit',personId,this.dataTransOpts.tableS.contact_person.id)
      if (personId) {
        let currentRow = {}
        let lfind = arrayExistObj(this.contactPersonList, 'id', personId)
        if (lfind > -1) {
          objCopy(this.curChooseRow, this.contactPersonList[lfind])
          currentRow = this.contactPersonList[lfind]
        } else{
          currentRow = deepCopy(this.curChooseRow)
          this.contactPersonList.push(currentRow)
        }
        
        setTimeout(() => {
          this.dataTransOpts.refresh.contact_method.M++
          this.$refs['contactPersonList'].setCurrentRow()
          this.$refs['contactPersonList'].setCurrentRow(currentRow)          
        }, 10)       
      }
    },

    rowClick(row) {      
      this.curChooseRow = deepCopy(row)      
      this.dataTransOpts.tableS.contact_person.id = row.id
      setTimeout(() => {
        this.dataTransOpts.refresh.contact_method.M++
      }, 20);
    },
  },

  watch: {
    // 单位id未变时，强制刷新
    "dataTransOpts.refresh.contact_person.M": {
      // immediate: true,
      handler(newVal, oldVal) {
        console.log(`watch 联系人 newVal:${newVal} oldVal:${oldVal} customerOrgId: ${this.dataTransOpts.tableS.customer_org.id}`);
        this.getContactPersonList(this.dataTransOpts.tableS.customer_org.id)
      }
    },

    // 单位id未变时，强制刷新
    "dataTransOpts.refresh.contact_method.M": {
      // immediate: true,
      handler(newVal, oldVal) {
        console.log(`watch 联系方式 newVal:${newVal} oldVal:${oldVal} contactPersonId: ${this.dataTransOpts.tableS.contact_person.id}`);
        // this.getContactPersonList(this.dataTransOpts.tableS.contact_person.id)
        this.getContactMethodList(this.dataTransOpts.tableS.contact_person.id);
      }
    },

    // 'customerOrgId' (newVal,oldVal){
    //   console.log('watch customerOrgId',newVal,oldVal)
    //   if(newVal != oldVal){
    //     this.personId = ''
    //   }
    // }
  },
};
</script>
<style scoped>
@import '../../assets/css/global_table.css';
@import '../../assets/css/global_input.css';
@import '../../assets/css/global_form.css';

.btnClass {
  width: 110px;
}
</style>
