<template>
  <el-dialog :title="props.title" v-model="isShowDetail" width="1120px"
    :before-close="() => confirmClose(!props.title.includes('详情'))">
    <div class="config">
      <el-form ref="ruleFormRef" label-width="auto" :model="info" label-suffix="：" :rules="rules"
        :disabled="props.title.includes('详情')" label-position="right">
        <el-row>
          <el-col :span="11">
            <el-form-item label="公司名称">
              <el-input v-model="info.orgName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="统计年度">
              <!-- <el-input v-model="info.reportingYear" disabled /> -->
              <el-select clearable v-model="info.reportingYear" disabled>
                <el-option v-for="item in filterYear(7)" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>                                                                                                                                            
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="上报季度" prop="reportCycleCode">
              <el-select clearable placeholder="请选择季度" v-model="info.reportCycleCode" :disabled="!props.isAdd">
                <el-option v-for="item in D_BZ_QUARTER" xgflx="09,10,15" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="驾驶员姓名" prop="bbEmployeeName">
              <el-input v-model="info.bbEmployeeName" />

              <!-- <XgfAndZzjgry v-model:ids="info.userId" v-model:cName="info.bbEmployeeName" :relatedid="null" isSingle
                :disabled="props.title.includes('详情')" @change="userChange" /> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="员工性别" prop="bbEmpSexCode">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_XB" v-model="info.bbEmpSexCode" selectType="select" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="出生日期" prop="bbBirthDate">
              <!-- <el-input v-if="!isAdd" v-model="info.bbBirthDate" /> -->
              <el-date-picker style="width: 100%;" v-model="info.bbBirthDate" type="data" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择出生日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="机动车辆准驾车型名称" prop="cdMotorCarAdmCode">
              <el-select v-model="info.cdMotorCarAdmCode" clearable>
                <el-option v-for="item in D_TB_DRIVELEVEL" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="人员类别名称" prop="bbEohPersonnelCategoryCode">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_ZYWHRYLB" v-model="info.bbEohPersonnelCategoryCode"
                selectType="select" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="驾驶证初次领证时间" prop="bbMotorCarDlTfDate">
              <!-- <el-input v-model="info.bbMotorCarDlTfDate" /> -->
              <el-date-picker style="width: 100%;" v-model="info.bbMotorCarDlTfDate" type="data" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择驾驶证初次领证时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 违章次数登记 -->
        <el-row>
          <el-col :span="24">
            <div class="violation-section">
              <el-table :data="violationList" border stripe style="width: 100%; margin-top: 10px;" height="350px">
                <el-table-column prop="trafficIllegalTypeName" label="违章类型"></el-table-column>
                <el-table-column prop="trafficIllegalNum" label="违章次数">
                  <template #default="{ row }">
                    <el-input-number v-model="row.trafficIllegalNum" :min="0" :max="999" :step="1" :precision="0" />
                  </template>
                </el-table-column>
                <!-- 清除 -->
                <el-table-column label="操作">
                  <template #default="{ row }">
                    <span class="operdel" size="small" @click="handleDelete(row)">
                      <el-icon>
                        <Delete />
                      </el-icon>
                      清零</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 选择人员 -->
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" :loading="saveLoading" @click="onSave" v-if="!props.title.includes('详情')" style="margin-right: 10px">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>确定</span></el-button>
        <el-button @click="closed"> <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span></el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, computed } from "vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
import { filterYear } from "@/utils/auth.js"
import XgfAndZzjgry from "@/views/dataReportWork/dljtgl/com/XgfAndZzjgry.vue"
const { proxy } = getCurrentInstance();
const { D_BZ_ZYWHRYLB, D_BZ_XB, D_BZ_QUARTER, D_TB_DRIVELEVEL } = proxy.$dict("D_BZ_ZYWHRYLB", "D_BZ_XB", "D_BZ_QUARTER", "D_TB_DRIVELEVEL");
const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  detail: {
    type: Object,
    default: () => { }
  },
  type: {
    type: String,
    default: ""
  },
  rowItem: {
    type: Object,
    defalut: () => ({})
  }
});
const emit = defineEmits(["close"]);
const isShowDetail = ref(true);
const ruleFormRef = ref();
const saveLoading = ref(false)
const isAdd = computed(() => {
  return props.title.includes('新增')
})
const rules = reactive({
  // ...rule.numbernineRule({ validator: true, require: true, iszs: true, firstNum: 8, lastNum: 2 }, "fsisBdArea"),
  // ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "fsisEmployPersonQty"),
  // 'fsisName': [{ required: true, message: '部位名称', trigger: 'blur' }],
  'reportCycleCode': [{ required: true, message: '请选择季度', trigger: 'blur' }],
  'bbEmployeeName': [{ required: true, message: '驾驶员姓名不能为空', trigger: 'blur' }],
  'bbEmpSexCode': [{ required: true, message: '员工性别不能为空', trigger: 'blur' }],
  'bbBirthDate': [{ required: true, message: '请选择出生日期', trigger: 'blur' }],
  'cdMotorCarAdmCode': [{ required: true, message: '机动车辆准驾车型名称不为空', trigger: 'blur' }],
  'bbEohPersonnelCategoryCode': [{ required: true, message: '人员类别名称不为空', trigger: 'blur' }],
  'bbMotorCarDlTfDate': [{ required: true, message: '请选择驾驶证初次领证时间', trigger: 'blur' }],
});
const info = ref({});

// 违章类型定义
const violationTypes = ref([
  { value: '0', label: '超载' },
  { value: '1', label: '超速' },
  { value: '2', label: '违章停车' },
  { value: '3', label: '违规变道' },
  { value: '4', label: '闯红灯' },
  { value: '5', label: '占用应急车道' },
  { value: '6', label: '未系安全带' },
  { value: '7', label: '操作不当' },
  { value: '8', label: '打手机' },
  { value: '9', label: '吸烟' },
  { value: '10', label: '疲劳驾驶' },
  { value: '11', label: '其他' }
]);

// 违章记录列表
const violationList = ref([]);

const handleDelete = (row) => {
  row.trafficIllegalNum = 0
}

const onSave = async () => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (Array.isArray(info.value.checkFileId) && info.value.checkFileId.length) {
        info.value.checkFileId = info.value.checkFileId.join(",")
      }
      if (Array.isArray(info.value.designFileId) && info.value.designFileId.length) {
        info.value.designFileId = info.value.designFileId.join(",")
      }
      if (Array.isArray(info.value.studyFileId) && info.value.studyFileId.length) {
        info.value.studyFileId = info.value.studyFileId.join(",")
      }
      /** 交通违法记录 */
      const violateEntityList = violationList.value.map(item => {
        return {
          trafficIllegalNum: item.trafficIllegalNum,
          trafficIllegalTypeCode: item.trafficIllegalTypeCode,
          trafficIllegalTypeName: item.trafficIllegalTypeName
        }
      })
      const params = {
        ...info.value,
        violateEntityList,
        bbEmpSexName: info.value.bbEmpSexCode && D_BZ_XB.value.find(item => item.value == info.value.bbEmpSexCode)?.label || '',
        cdMotorCarAdmName: info.value.cdMotorCarAdmCode && D_TB_DRIVELEVEL.value.find(item => item.value == info.value.cdMotorCarAdmCode)?.label || '',
        bbEohPersonnelCategoryName: info.value.bbEohPersonnelCategoryCode && D_BZ_ZYWHRYLB.value.find(item => item.value == info.value.bbEohPersonnelCategoryCode)?.label || ''
      }
      saveLoading.value = true
      const url = isAdd.value ? '/mosty-jcgl/data/driver/saveDriver' : '/mosty-jcgl/data/driver/editDriver'
      postApi(params, url)
        .then(() => {
          ElMessage.success("保存成功");
          emit("close", true);
        })
        .finally(() => {
          saveLoading.value = false
        });
    }
  });
};
const userChange = (val) => {


}

/** 设置违章记录 */
const getViolationList = (arr) => {
  arr = Array.isArray(arr) ? arr : []
  return violationTypes.value.map(item => {
    let find = arr.find(item2 => item2.trafficIllegalTypeCode == item.value) || {}
    return {
      trafficIllegalNum: find.trafficIllegalNum || 0,
      trafficIllegalTypeCode: item.value,
      trafficIllegalTypeName: item.label
    }
  })

}
onMounted(() => {
  if (isAdd.value) {
    info.value = {
      orgCode: props.rowItem.orgCode && props.rowItem.orgCode.replace('XN', ''),
      orgName: props.rowItem.orgName,
      statId: props.rowItem.id,
      reportingYear: String(props.rowItem.reportingYear || ''),
      reportCycleCode: String(props.rowItem.reportCycleCode || '')
    }
    violationList.value = getViolationList([])
  } else if (props.type == 'report') {
    info.value = props.detail
  } else {
    getApi({}, `/mosty-jcgl/data/driver/selectOne/${props.detail.sourceId}`).then((res) => {
      res = res ? res : {}
      info.value = {
        ...res,
        reportingYear: String(props.rowItem.reportingYear || ''),
        reportCycleCode: String(props.rowItem.reportCycleCode || ''),
        bbEmpSexCode: res.bbEmpSexName ? (res.bbEmpSexName == '男'||'1' ? '1' : '2') : '',
      };
      console.log(info.value, 'info.value')
      violationList.value = getViolationList(res.violateEntityList)
    });
  }

});
const closed = () => {
  if(!ruleFormRef.value) return
  if (!props.title.includes('详情')) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emit("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    emit("close");
  }

};
</script>
<style scoped lang="scss">
::v-deep .el-dialog__body {
  height: 100% !important;
}

.config {
  height: calc(84vh - 120px);
  overflow-y: auto;
}

::v-deep .el-form-item--default {
  margin-left: 10px;
}
</style>
