<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addOrEditDialogFlag"
    :title="title"
    :append-to-body="false"
    :close-on-click-modal="false"
    width="70%"
    :before-close="cancel"
  >
    <el-form ref="form" :rules="rules" class="el-form-box" :model="form" label-width="120px">
      <headerTitle title="基本信息"></headerTitle>
      <el-row :gutter="12">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item
              label="发票类型"
              prop="type">
              <el-select v-model="form.type" @change="handleSelType" :disabled="isOtherSourceFlag" clearable
                         style="width: 100%">
                <el-option label="开票" :value="1"></el-option>
                <el-option label="收票" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!--        <el-col :span="12">-->
          <!--          <el-form-item-->
          <!--            label="会计科目"-->
          <!--            prop="accountingSubjectId"-->
          <!--            -->
          <!--          >-->
          <!--            <ele-tree-select-->
          <!--              clearable-->
          <!--              filterable-->
          <!--              ref="treeSelect"-->
          <!--              :data="accountingSubjectList"-->
          <!--              v-model="form.accountingSubjectId"-->
          <!--              valueKey="id"-->
          <!--              labelKey="name"-->
          <!--              placeholder="请选择"-->
          <!--              @change="changeSubjectInfo"-->
          <!--              default-expand-all-->
          <!--            />-->
          <!--          </el-form-item>-->
          <!--        </el-col>-->
          <el-col :span="12">
            <el-form-item
              label="金额"
              prop="amount"
              >
              <el-input-number v-model="form.amount" :precision="2" :controls="false" style="width: 100%"
                               :min="0"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="12">
          <el-form-item
            label="申请部门"
            prop="applyDeptId">
            <ele-tree-select
              clearable
              :data="deptTreeList"
              v-model="form.applyDeptId"
              valueKey="id"
              labelKey="name"
              placeholder="请选择"
              @change="changeDeptInfo"
              default-expand-all
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="申请人"
            prop="applyUserId">
            <personSelect
              ref="directorRef"
              v-model="form.applyUserId"
              @selfChange="changeUserInfo"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            label="预计开票日期"
            >
            <el-date-picker
              style="width: 100%"
              v-model="form.expectInvoiceDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item prop="repliedFiles" label="附件">-->
        <!--            <fileUpload-->
        <!--              v-model="form.files"-->
        <!--              module="main"-->
        <!--              :showLib="false"-->
        <!--              :limit="10"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
      </el-row>
      <headerTitle title="开票信息"></headerTitle>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            label="公司名称"
            prop="companyName"
            >
            <el-input v-model="form.companyName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="统一社会信用代码"
            prop="companyUsc"
            class="form_item_label"
            >
            <el-input v-model="form.companyUsc"></el-input>
          </el-form-item>
        </el-col>


      </el-row>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            label="开户银行"
            prop="companyBankBranchNo"
            >
            <el-input v-model="form.companyBankBranchNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">

          <el-form-item
            label="银行账户"
            prop="companyBankAccount"
            >
            <el-input v-model="form.companyBankAccount"></el-input>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            label="单位地址"
            prop="companyAddress"
            >
            <el-input v-model="form.companyAddress"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="电话号码"
            prop="companyTel"
            >
            <el-input v-model="form.companyTel"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <headerTitle title="收票信息"></headerTitle>


      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            label="收票人"
            prop="receiverName"

          >
            <el-input v-model="form.receiverName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="收票人地址"
            prop="receiverAddress"

          >
            <el-input v-model="form.receiverAddress"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            label="联系方式"
            prop="receiverTel"

          >
            <el-input v-model="form.receiverTel"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <headerTitle title="关联信息"></headerTitle>
    <table-info v-if="(dialogType!='add'&&form.detailList.length)||dialogType=='add'"
                :isOtherSourceFlag="isOtherSourceFlag" :dialogType="dialogType"
                :form="form" ref="table" @setPrice="setPrice"></table-info>
    <div slot="footer">
      <el-button type="primary" @click="handleSave(0)">保存</el-button>
      <el-button type="primary" @click="handleSave(1)">提交</el-button>
      <el-button @click="cancel">返回</el-button>
    </div>

  </ele-modal>
</template>
<script>
import personSelect from "@/components/CommomSelect/person-select.vue";
import {listOrganizations} from "@/api/system/organization";
import {mapGetters} from "vuex";
import fileUpload from "@/components/upload/fileUpload.vue";
import tableInfo from "./tableInfo.vue";
import {getTreeByPid} from "@/api/classifyManage";
import {
  invoiceApplyInfoAPI,
  invoiceApplySaveAPI,
  invoiceApplySubmit,
  invoiceApplyUpdateAPI
} from "@/api/financialManage/invoiceManage";


export default {
  name: "add-or-edit-dialog",
  components: {
    fileUpload,
    personSelect,
    tableInfo
  },
  props: {
    addOrEditDialogFlag: {
      type: Boolean,
      default: false
    },
  },
  provide() {
    return {
      invoiceType: () => this.form.type
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  data() {
    return {
      dialogType: '',
      title: '',
      isOtherSourceFlag: false,
      form: {
        id:'',
        accountingSubjectCode: "",
        accountingSubjectId: '',
        accountingSubjectName: "",
        amount: undefined,
        applyDeptId: '',
        applyDeptName: "",
        applyUserId: '',
        applyUserName: "",
        companyAddress: "",
        companyBankAccount: "",
        companyUsc: "",
        expectInvoiceDate: "",
        companyBankBranchNo: "",
        companyName: "",
        receiverAddress: "",
        receiverName: "",
        receiverTel: "",
        companyTel: "",
        detailList: [],
        drawerId: '',
        drawerName: "",
        files: [],
        invoiceStatus: '',
        link: [],
        remark: "",
        settlementAccountId: '',
        settlementAccountName: "",
        type: ''
      },
      feeTypeList: [],
      accountingSubjectList: [],
      deptList: [],
      deptTreeList: [],
      rules: {
        applyDeptId: {required: true, message: '请选择', trigger: 'change'},
        applyUserId: {required: true, message: '请选择', trigger: 'change'},
        accountingSubjectId: {required: true, message: '请选择', trigger: 'change'},
        feeTypeId: {required: true, message: '请选择', trigger: 'change'},
        amount: {required: true, message: '请输入', trigger: 'blur'},
        companyName: {required: true, message: '请输入', trigger: 'blur'},
        type: {required: true, message: '请选择', trigger: 'change'},
      }
    }
  },
  created() {

  },
  methods: {
    //从发票管理新增发票初始化
    async init(row = {}, type) {
      this.title = type == 'add' ? '新增' : '修改'
      this.dialogType = type
      await this.getClassifyList(24, 'accountingSubjectList')
      await this.getDeptList()
      if (type == 'add') {
        this.form.applyDeptId = this.user.info.groupId;
        this.form.applyDeptName = this.user.info.groupName;
        this.form.applyUserId = this.user.info.userId;
        this.form.applyUserName = this.user.info.name;
      } else {
        await this.getInfo(row.id)
      }
      this.$nextTick(async () => {
        await this.getUserList(this.form.applyDeptId);
      })
    },
    //从其他来源新增发票初始化
    createInvoice(row = {}, invoiceType, tableInfo = {}, isOtherSourceFlag = true, dialogType = 'add',) {
      this.form.type = invoiceType
      this.isOtherSourceFlag = isOtherSourceFlag
      this.dialogType = dialogType
      this.init(row, dialogType)


      setTimeout(() => {
        this.$nextTick(() => {
          this.$refs.table.getAccountData(tableInfo)
        })
      }, 400)

    },
    //获取详情
    async getInfo(id) {
      this.form = await invoiceApplyInfoAPI(id)
    },

    //获取分类管理中的数据
    async getClassifyList(id, listName) {
      let res = await getTreeByPid(id)
      this[listName] = res.data
    },
    //获取费用类别选中数据
    changeFeeTypeInfo(val) {
      if (!val) {
        this.form.feeTypeName = ''
        this.form.feeTypeCode = ''
      }
      let data = this.$refs.feeTypeTree?.$refs?.tree?.getCurrentNode() || {}
      this.form.feeTypeName = data.name
      this.form.feeTypeCode = data.code
    },
    //获取会计科目选中数据
    changeSubjectInfo(val) {
      if (!val) return this.form.accountingSubjectName = ''
      let data = this.$refs.treeSelect?.$refs?.tree?.getCurrentNode() || {}
      this.form.accountingSubjectName = data.name
    },
    // 获取部门数据
    getDeptList() {
      listOrganizations().then((list) => {
        this.deptList = list;
        this.deptTreeList = this.$util.toTreeData({
          data: list,
          idField: 'id',
          parentIdField: 'parentId'
        });
      });
    },
    // 选择负责人部门
    changeDeptInfo(id) {
      const info = this.deptList.find((e) => e.id == id) || {};
      this.form.applyDeptName = info.name;
      this.form.applyUserId = '';
      this.form.applyUserName = '';
      this.getUserList(id);
    },
    // 获取人员数据
    getUserList(deptId) {
      if (deptId) {
        this.$refs.directorRef.getList({deptId});
      }
    },
    //选择人员数据
    changeUserInfo(val, info) {
      this.form.applyUserName = info.name;
    },
    //选择人员数据
    changDrawerName(val, info) {
      this.form.drawerName = info.name;
    },
    //
    handleSelType(val) {
      this.$refs.table.clearTable()
    },
    setPrice(val) {
      this.form.amount = val
    },
    //
    handleSave(flag) {
      this.$refs.form.validate(async valid => {
        if (!valid) return this.$message.warning('有必填项未填，请检查')
        let tableData = await this.$refs.table.getTableValidate()
        this.form.link = tableData.link
        this.form.detailList = tableData.detailList
        const API = this.dialogType == 'add' ? invoiceApplySaveAPI : invoiceApplyUpdateAPI
        const id = await API(this.form)
        if (flag) {
          await this.handleSub(id)
        }
        this.$message.success('操作成功')
        this.done()
        this.cancel()
      })
    },
    //提交-开启流程
    async handleSub(id='') {
      try {
        await invoiceApplySubmit({businessId: id||this.form.id, type: this.form.type,})
      } catch (e) {
        this.$message.error(e.message);
      }
    },
    //刷新主列表数据
    done() {
      this.$emit('reload')
    },
    //关闭弹窗
    cancel() {
      this.$emit('update:addOrEditDialogFlag', false)
    }
  }
}
</script>
<style scoped lang="scss">

</style>
