<template>
  <div class="table-box">
    <div class=" bg-white pt-2 pl-2">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane
            :label="item.label"
            :name="item.value"
            v-for="(item, index) in ContractStatus"
            :key="index"
          >
          <template #label>
            <div>
              {{item.label}}
            <!-- <span style="font-size: 20px; font-weight: bold;">{{item.msg}}</span> -->
            </div>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>
    <ProTable ref="proTable" :config="config" :api="getContractPage" :paramCallback="paramCallback" :selectdList="selectdList">
      <template #left_buttons>
        <el-button type="primary" @click="addConstant()">新建合同</el-button>
      </template>
    </ProTable>
    <addModel
      ref="addModelRef"
      @success="query"
    ></addModel>
    <vxe-modal
      resize
      v-model="showModal"
      :title="currentType === 'finance' ? '财务审批' : '法务审批'"
      height="482"
      width="550"
      show-footer
      esc-closable
    >
      <div class="w-full px-3 h-full overflow-auto flex-col flex mytable">
        <el-form
            ref="formRef"
            :model="form"
            >
            <el-row :gutter="20">
                <el-col :span="12">
                <el-form-item label="合同编号：" prop="name">
                    {{form.contractNo}}
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item class="w-full" label="合同签订主体：" prop="code">
                    {{form.contractSignBody}}
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item class="w-full" label="业务名称：" prop="code">
                    {{form.businessName}}
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item class="w-full" label="客户名称：" prop="code">
                   {{form.customerName}}
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item class="w-full" label="身份证号：" prop="idCard">
                    {{form.idCard}}
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item class="w-full" label="服务费总额：" prop="code">
                    {{form.serviceFeeTotal}}
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item class="w-full" label="服务期限：" prop="code">
                    {{form.serviceTerm}}
                </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="审核意见：" prop="name">
                      <el-input
                      v-model="form.financeRepairOpinion" v-if="currentType === 'finance'" type="textarea"
                      placeholder="请输入"
                      />
                      <el-input
                      v-model="form.legalRepairOpinion" v-else type="textarea"
                      placeholder="请输入"
                      />
                  </el-form-item>
                </el-col>
            </el-row>
        </el-form>
      </div>
      <template #footer>
        <el-button type="default" @click="showModal = false">取消</el-button>
        <el-button type="danger" @click="submitForm('fail')">拒绝</el-button>
        <el-button type="primary" @click="submitForm('pass')">审批通过</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script setup lang="jsx" name="platformManage">
  import { ref, reactive, onMounted, computed } from 'vue';
  import { Plus, Delete, Edit, Setting } from '@element-plus/icons-vue';
  import { getContractPage, flowStatusByIds  } from '@/api/customer';
  import { ElMessageBox, ElMessage, ElButton, ElTag } from 'element-plus';
  import { useRouter } from 'vue-router';
  import addModel from './components/addModel.vue';
  import { useDict } from '@/hooks/useDict';
  import { useAuthStore } from '@/stores/modules/auth';
  import { useUserStore } from '@/stores/modules/user';

  const activeName = ref('created');
  const userStore = useUserStore();
  const { authButtonListGet } = useAuthStore(); // 获取用户权限列表
  const { PaymentForm, ContractStatus, FlowStatus } = useDict("PaymentForm", "ContractStatus", "FlowStatus");
  const addModelRef = ref()
  const proTable = ref(null);
  const selectdList = ref([]);
  const form = ref()
  const showModal = ref(false)
  const currentType = ref();
  const onCheckboxChange = (row) => {
    selectdList.value = row.records;
  };
  const router = useRouter();
  const query = () => proTable.value?.search();

  const paramCallback = (param) => {
    const obj = JSON.parse(JSON.stringify(param));
    if (obj['createTime']) {
      if (obj['createTime'][0]) obj['createTimeBegin'] = obj['createTime'][0];
      if (obj['createTime'][1]) obj['createTimeEnd'] = obj['createTime'][1];
      delete obj['createTime'];
    }
    obj['contractStatus'] = activeName.value;
    return obj;
  };
  const onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
  };
  const addConstant = (row, edit = false) => {
    addModelRef.value.openModal(row, edit
    );
  };
  const apply = (row, type) => {
    currentType.value = type
    form.value = row
    showModal.value = true
  }
  const submitForm = (type) => {
    const param = {
      ids: form.value.id
    }
    if (currentType.value === 'finance') {
      param['financeRepairOpinion'] = form.value.financeRepairOpinion
      param['financeFlowStatus'] = type
    } else {
      param['legalRepairOpinion'] = form.value.legalRepairOpinion
      param['legalFlowStatus'] = type
    }
    flowStatusByIds(param).then(res => {
      if(res.success) {
          ElMessage.success({
          message: '审核成功',
          plain: true,
        });
        showModal.value = false
        query()
      }
    })
  }
  const handleClick = () => {
    setTimeout(() => {
      query();
    }, 300);
  };
  const config = computed(() => {
    return {
    onCheckboxChange: onCheckboxChange,
    onCheckboxAll: onCheckboxAll,
    columns: [
      // { type: 'checkbox', width: 60,fixed: 'left' },
      { field: 'id', title: '档案编号', type: 'seq',width: 80
      },
      { field: 'id', title: '合同编号', width: 140, search: { labelWidth: 85, el: 'input' }, slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <div
                  onClick={() => addConstant(row)}
                  className=" text-blue-400 cursor-pointer inline-block"
                >
                  {row.contractNo}
                </div>
              </>
            );
          },
        }  
      },
      {
        field: 'contractSignBody',
        title: '合同签订主体',
        width: 120,
        search: { labelWidth: 85, el: 'input' }
      },
      {
        field: 'businessName',
        title: '业务名称',
        width: 120,
        search: { el: 'input',labelWidth: 85,  props: { clearable: true } },
      },
      { field: 'customerName', title: '客户名称',width: 100, search: { labelWidth: 85, el: 'input' } },
      { field: 'idCard', title: '身份证号',width: 150, search: { labelWidth: 85, el: 'input' } },
      {
        field: 'paymentForm',
        title: '缴费形式',
        showOverflow: 'tooltip',
        width: 80,
        enum: PaymentForm,
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.paymentForm
                  ? PaymentForm.value?.find((v) => v.value === row.paymentForm)?.label
                  : ''}
              </>
            );
          },
        },
      },
      { field: 'serviceFeeTotal', title: '服务费总额',width: 100, search: { labelWidth: 85, el: 'input' } },
      { field: 'serviceTerm', title: '服务期限', width: 100,search: { labelWidth: 85, el: 'input' } },
      // { field: 'contractScanFile', title: '合同扫描件', search: { labelWidth: 85, el: 'input' } },
      { field: 'createTime', title: '创建日期', width: 140, search: {
        el: 'date-picker',
        labelWidth: 85, 
        props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
      }, },
      { field: 'user.username', width: 90,title: '创建人' },
      { field: 'contractStatus', title: '合同状态', showOverflow: 'tooltip',
        width: 80,
        enum: ContractStatus,
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.contractStatus
                  ? ContractStatus.value?.find((v) => v.value === row.contractStatus)?.label
                  : ''}
              </>
            );
          },
        }, },
      { field: 'financeFlowStatus', title: '财务审核状态', showOverflow: 'tooltip',
        width: 80,
        enum: FlowStatus,
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.financeFlowStatus
                  ? FlowStatus.value?.find((v) => v.value === row.financeFlowStatus)?.label
                  : ''}
              </>
            );
          },
        }, },
      { field: 'remark', title: '操作', fixed: 'right',width: 160,visible: activeName.value !== 'completed',
        slots: {
          default({ row }) {
            return (
              <>
                <ElButton type="primary" link onClick={() => addConstant(row, true)} v-show={row.createBy === userStore.userInfo.id} disabled={row.financeFlowStatus=== 'pass'}>
                  修改
                </ElButton>
                <ElButton type="primary" link onClick={() => apply(row, 'finance')} v-show={authButtonListGet.includes('finance_apply')} disabled={row.legalFlowStatus || row.financeFlowStatus === 'pass'}>
                  财务审批
                </ElButton>
                {/* <ElButton type="primary" link onClick={() => apply(row, 'legal')} v-show={authButtonListGet.includes('legal_apply')} disabled={row.financeFlowStatus !== 'pass' || row.legalFlowStatus === 'pass'}>
                  法务审批
                </ElButton> */}
              </>
            );
          },
        }, },
    ],
  };
  });


  onMounted(() => {
    query();
  });
</script>
