<template>
  <section class="custom-page">
    <h2>农机基本信息</h2>
    <TypeMenu v-if="materialTypes['5'].length > 1" v-model:type="_type" :types="materialTypes['5']" />
    <br />
    <avue-crud
      ref="crudRef"
      v-model:page="pageData"
      v-model:search="searchCondition"
      :table-loading="_loading"
      :before-close="handleCloseDialog"
      :data="tableData"
      :option="option"
      @search-change="
        (form, done) => {
          getData(1);
          done();
        }
      "
      @search-reset="getData(1)"
      @refresh-change="getData"
      @current-change="getData"
      @size-change="getData(1)"
      @row-save="handleRowSave"
      @row-update="handleRowUpdate"
    >
      <template #menu="scope">
        <custom-table-operate :actions="actions" :data="scope" />
      </template>
      <template #photoUrl-form="{ type }">
        <Attrs v-model:attrs="attrs" :type="type == 'add' ? 'add' : 'view'" :limit="2" />
      </template>
      <template #detectionUnit-form="{ type }">
        <section v-if="type == 'edit'" style="display: flex; width: 100%">
          <span style="width: calc(50% - 85px); height: 32px">
            <el-input v-model="checkUnitStamp" placeholder="请输入 检测单位"></el-input>
          </span>
          &emsp;
          <Attrs v-model:attrs="checkAttrs" style="flex: 1" type="add" :up-btn="checkAttrs < 1" :file-num="2" :limit="1" />
        </section>
        <section v-if="type == 'view'" style="position: relative">
          {{ checkUnitStamp }}
          <img :src="checkAttrs[0]?.url ?? ''" alt="" style="position: absolute; bottom: -10px; right: -10px" />
        </section>
      </template>
      <template #viewReport-form>
        <section style="text-align: center; line-height: 58px">
          <el-button type="primary" @click="handleCheckInfo(true)">查看报告</el-button>
        </section>
      </template>
      <template #closeReport-form="{ type }">
        <section v-if="type == 'view'" style="text-align: center; line-height: 58px">
          <el-button type="primary" @click="handleCheckInfo()">关闭</el-button>
        </section>
      </template>
    </avue-crud>
  </section>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import TypeMenu from '../../common/TypeMenu.vue';
import { CRUD_OPTIONS, pageData, customRules } from '@/config';
import { useBasicInfo } from '@/views/inputSuppliesManage/hooks/useBasicInfo';
import Attrs from '@/views/inputSuppliesManage/common/Attrs.vue';
import inputSuppliesApi from '@/apis/inputSuppliesApi';
import { ElMessage } from 'element-plus';
import assistFn from '@/views/inputSuppliesManage/hooks/useAssistFn';
const { deleteFn } = new assistFn();
const { loadFinish, materialTypes, targetName } = useBasicInfo({
  moduleType: '5',
});
const { getMachineryList, addMachinery, delMachinery, machineryReport } = inputSuppliesApi;
const _allTypes = ref([]);
watch(
  () => loadFinish.value,
  (bol) => {
    if (bol) {
      option.value.column.forEach((v) => {
        if (v.prop === '_classifyId') {
          _allTypes.value = materialTypes['5'].filter((v, i) => i > 0) ?? [];
          v.dicData = _allTypes.value;
        }
      });
    }
  }
);
onMounted(getData);
/* --------------- data --------------- */
// #region
const _type = ref('0');
const crudRef = ref();
const _loading = ref(true);
const searchCondition = ref({
  keywords: '',
});
const customize = reactive([
  {
    label: '可定制',
    value: '0',
  },
  {
    label: '不可定制',
    value: '1',
  },
]);
const afterService = reactive([
  {
    label: '全国联保',
    value: '1',
  },
  {
    label: '国家三包规定',
    value: '2',
  },
  {
    label: '品牌官方售后',
    value: '3',
  },
  {
    label: '上门服务',
    value: '4',
  },
  {
    label: '远程技术支持',
    value: '5',
  },
  {
    label: '依旧换新',
    value: '6',
  },
]);
const subsidy = reactive([
  {
    label: '有补贴',
    value: '1',
  },
  {
    label: '无补贴',
    value: '0',
  },
]);
const tableData = ref([{}]);
const option = ref({
  ...CRUD_OPTIONS,
  dialogWidth: '50%',
  selection: false,
  column: [
    {
      label: '农机名称',
      prop: 'keywords',
      hide: true,
      search: true,
      addDisplay: false,
      viewDisplay: false,
      editDisplay: false,
    },
    {
      _customKey: 1,
      label: '农机名称',
      prop: 'njName',
      rules: customRules({ msg: '请输入农机名称' }),
      editDisplay: false,
    },
    {
      _customKey: 1,
      label: '品牌',
      prop: 'brand',
      rules: customRules({ msg: '请输入品牌' }),
      editDisplay: false,
    },
    {
      _customKey: 1,
      hide: true,
      label: '农机图片',
      prop: 'photoUrl',
      editDisplay: false,
    },
    {
      _customKey: 1,
      prop: 'manufacturer',
      label: '厂家',
      rules: customRules({ msg: '请输入厂家名称' }),
      editDisplay: false,
    },
    {
      _customKey: 1,
      prop: 'distributor',
      label: '经销商',
      editDisplay: false,
    },
    {
      hide: true,
      label: '分类',
      prop: '_classifyId',
      type: 'cascader',
      expandTrigger: 'click',
      dicData: [],
      rules: customRules({ msg: '请选择分类' }),
      editDisplay: false,
      viewDisplay: false,
      render: ({ row }) => row.classifyName,
    },
    {
      _customKey: 1,
      label: '分类',
      prop: 'classifyName',
      addDisplay: false,
      editDisplay: false,
    },
    {
      _customKey: 1,
      hide: true,
      label: '驱动方式',
      prop: 'powerType',
      editDisplay: false,
    },
    {
      _customKey: 1,
      hide: true,
      label: '加工定制',
      prop: 'customize',
      type: 'select',
      dicData: customize,
      editDisplay: false,
    },
    {
      _customKey: 1,
      hide: true,
      label: '农机补贴',
      prop: 'subsidy',
      type: 'select',
      dicData: subsidy,
      editDisplay: false,
    },
    {
      _customKey: 1,
      hide: true,
      label: '质保期',
      prop: 'expiryDate',
      editDisplay: false,
    },
    {
      _customKey: 1,
      hide: true,
      label: '售后服务',
      prop: 'afterService',
      type: 'select',
      dicData: afterService,
      multiple: true,
      value: [],
      editDisplay: false,
    },
    {
      _customKey: 1,
      hide: true,
      label: '主要特点',
      prop: 'mainFeature',
      span: 24,
      type: 'textarea',
      editDisplay: false,
    },
    {
      _customKey: 1,
      hide: true,
      label: '功能配置',
      prop: 'functionConfig',
      span: 24,
      type: 'textarea',
      editDisplay: false,
    },
    {
      _customKey: 1,
      hide: true,
      label: '适用范围',
      prop: 'adaptScope',
      span: 24,
      type: 'textarea',
      editDisplay: false,
    },
    {
      _customKey: 1,
      hide: true,
      labelWidth: 0,
      prop: 'viewReport',
      addDisplay: false,
      editDisplay: false,
      span: 24,
    },
  ],
  group: [
    {
      label: '基本信息',
      prop: 'basicInfo',
      addDisplay: false,
      viewDisplay: false,
      column: [
        {
          label: '农机型号',
          prop: 'njModel',
          rules: customRules({ msg: '请输入农机型号' }),
        },
        {
          label: '农机牌照号',
          prop: 'licenseNumber',
          rules: customRules({ msg: '请输入农机牌照号' }),
        },
        {
          label: '权属人',
          prop: 'owner',
          rules: customRules({ msg: '请输入权属人' }),
        },
        {
          label: '联系电话',
          prop: 'phone',
          rules: customRules({ msg: '请输入联系电话' }),
        },
        {
          label: '联系地址',
          prop: 'address',
          rules: customRules({ msg: '请输入联系地址' }),
        },
      ],
    },
    {
      label: '年检信息',
      prop: 'yearCheckInfo',
      addDisplay: false,
      viewDisplay: false,
      column: [
        {
          label: '年检地点',
          prop: 'detectionAddress',
          rules: customRules({ msg: '请输入年检地点' }),
        },
        {
          label: '年检时间',
          prop: 'detectionTime',
          type: 'date',
          valueFormat: 'YYYY-MM-DD',
          format: 'YYYY-MM-DD',
          rules: customRules({ msg: '请输入年检时间' }),
        },
        {
          label: '外观检查',
          prop: 'inspection',
          span: 24,
          type: 'textarea',
          rules: customRules({ msg: '请输入外观检查' }),
        },
        {
          label: '技术检测',
          prop: 'technicalDetection',
          span: 24,
          type: 'textarea',
          rules: customRules({ msg: '请输入技术检测' }),
        },
        {
          label: '安全装置检查',
          prop: 'safetyDetector',
          span: 24,
          type: 'textarea',
          rules: customRules({ msg: '请输入安全装置检' }),
        },
      ],
    },
    {
      label: '年检结论',
      prop: 'yearCheckResult',
      addDisplay: false,
      viewDisplay: false,
      column: [
        {
          label: '结论',
          prop: 'conclusion',
          rules: customRules({ msg: '请输入结论' }),
        },
        {
          label: '检测员签名',
          prop: 'signature',
          rules: customRules({ msg: '请输入检测员签名' }),
        },
        {
          label: '检测单位盖章',
          prop: 'detectionUnit',
          span: 24,
          rules: customRules({ disabled: true, otherRules: [{ required: true, message: '', validator: handleDetection }] }),
        },
        {
          labelWidth: 0,
          label: '',
          prop: 'closeReport',
          span: 24,
        },
      ],
    },
  ],
});
const actions = reactive([
  {
    name: '上传报告',
    icon: 'view',
    event: ({ row }) => handleCheck(row),
  },
  {
    name: '详情',
    icon: 'view',
    event: ({ row }) => handleInfo(row),
  },
  {
    type: 'danger',
    name: '删除',
    icon: 'delete',
    event: ({ row }) => deleteFn(row.id, delMachinery, getData),
  },
]);
const attrs = ref([]);
const checkUnitStamp = ref('');
const checkAttrs = ref([]);

// #endregion

/* --------------- methods --------------- */
// #region
function handleDetection(rule, value, callback) {
  if (!checkUnitStamp.value || !checkAttrs.value.length) {
    callback(new Error());
  } else {
    callback();
  }
}
async function getData(reset) {
  _loading.value = true;
  reset == 1 && (pageData.value.currentPage = 1);
  let params = {
    current: pageData.value.currentPage,
    size: pageData.value.size,
    njName: searchCondition.value.keywords,
  };
  _type.value != '0' && (params.classifyId = _type.value);
  let res = await getMachineryList(params);
  _loading.value = false;
  if (res.code == 200) {
    tableData.value = res.data.records;
    pageData.value.total = res.data.total;
  }
}

function handleCheck(row) {
  handleOtherInfo(row);
  handleReportSpan(24);
  crudRef.value.rowEdit(row);
}
function handleInfo(row) {
  handleSpanChange(true);
  handleOtherInfo(row);
  crudRef.value.rowView(row);
}
async function handleRowUpdate(form, index, done, loading) {
  let data = {
    id: form.id,
    njModel: form.njModel,
    licenseNumber: form.licenseNumber,
    owner: form.owner,
    phone: form.phone,
    address: form.address,
    detectionAddress: form.detectionAddress,
    detectionTime: form.detectionTime,
    inspection: form.inspection,
    technicalDetection: form.technicalDetection,
    safetyDetector: form.safetyDetector,
    conclusion: form.conclusion,
    signature: form.signature,
    detectionUnit: checkUnitStamp.value,
    sealUrl: checkAttrs.value[0].url,
  };
  let res = await machineryReport(data);
  loading();
  if (res.code == 200) {
    ElMessage.success('报告上传成功');
    done();
  }
}
async function handleRowSave(form, done, loading) {
  let data = {
    njName: form.njName,
    brand: form.brand,
    photoUrl: attrs.value.map((v) => v.url).join(','),
    powerType: form.powerType,
    manufacturer: form.manufacturer,
    distributor: form.distributor,
    customize: form.customize,
    afterService: form.afterService.join(),
    expiryDate: form.expiryDate,
    subsidy: form.subsidy,
    mainFeature: form.mainFeature,
    functionConfig: form.functionConfig,
    adaptScope: form.adaptScope,
  };
  data.classifyId = JSON.stringify(form._classifyId);
  data.classifyName = targetName(_allTypes.value, form._classifyId, '');
  let res = await addMachinery(data);
  loading();
  if (res.code == 200) {
    ElMessage.success('新增成功');
    getData();
    clearAttrs();
    done();
  }
}
function handleCheckInfo(open = false) {
  option.value.column.forEach((v) => {
    if (v._customKey == 1) v.viewDisplay = !open;
  });
  option.value.group.forEach((v) => {
    v.viewDisplay = open;
  });
}
/* 处理展示附件 */
function handleOtherInfo(row = {}) {
  if (!row) {
    return;
  }
  checkUnitStamp.value = row.detectionUnit;
  if (row.photoUrl) {
    attrs.value = row.photoUrl.split(',').map((v, i) => {
      return {
        url: v,
        uid: `photo_${i}_${Date.now()}`,
      };
    });
  }
  if (row.sealUrl) {
    checkAttrs.value = [
      {
        url: row.sealUrl,
        uid: `seal_${Date.now()}`,
      },
    ];
  }
}
function clearAttrs() {
  attrs.value = [];
  handleReportSpan(12);
}
function handleCloseDialog(done) {
  attrs.value = [];
  done();
}
function handleSpanChange(bol = false) {
  let arr1 = ['photoUrl', 'afterService'];
  option.value.column.forEach((v) => {
    if (arr1.includes(v.prop)) {
      if (bol) v.span = 24;
      else delete v.span;
    }
  });
}
function handleReportSpan(s = 12) {
  option.value.group[2].column[0].span = s;
  option.value.group[2].column[1].span = s;
}
// #endregion
</script>

<style lang="scss" scoped>
h2 {
  font-size: 24px;
  font-weight: bold;
  font-family: '黑体';
}
</style>
