<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="修程" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                disabled
                type="list"
                v-model="model.rapairRange"
                dictCode="repair_range"
                placeholder="请选择修程"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="设备" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceTypeId">
              <j-dict-select-tag
                disabled
                type="list"
                v-model="model.deviceTypeId"
                dictCode="bu_device_type,type_name,id"
                placeholder="请选择设备"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="部件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depard">
              <a-tree-select
                v-model="model.depard"
                :tree-data="departs"
                placeholder="请选择部件"
                tree-default-expand-all
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="序号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dispOrder">
              <a-input-number :min="1" v-model="model.dispOrder" placeholder="请输入序号" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="技能级别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="skillLevelArr">
              <j-dict-select-tag
                type="checkbox"
                v-model="model.skillLevelArr"
                dictCode="skill_level"
                placeholder="请选择允许操作的技能级别"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="检修要求" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="content">
              <a-textarea v-model="model.content" rows="4" placeholder="请输入检修要求" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="质检要求" :labelCol="labelCol1" :wrapperCol="labelCol1">
              <a-checkbox-group v-model="model.inspections" :options="inspactionOptions" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="检查类型" :labelCol="labelCol2" :wrapperCol="wrapperCol1">
              <FlexRadio
                v-model="model.checkType"
                :options="radiOptions"
                @change="changeCheckType"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="测量项" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-switch :checked="model.measure === '1'" checked-children="有" un-checked-children="无" @change="changeMeasure(model.measure)" />
              <a-button @click="handleAddMeasure(model.id,model.deviceTypeId)" v-if="model.measure==='1'" style="margin-left: 10px">添加测量项</a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <measure-item-modal ref="measureModal" @ok="measureSelected"></measure-item-modal>
  </a-spin>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import MeasureItemModal from '@views/regular/modules/MeasureItemModal.vue'
import { TreeSelect } from 'ant-design-vue'
import FlexRadio from '@views/regular/components/FlexRadio/index.vue'
export default {
  name: 'RegularDetailForm',
  components: { FlexRadio, MeasureItemModal },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      inspactionOptions: [
        {
          label: '专检',
          value: 1,
        },
        {
          label: '互检',
          value: 2,
        },
      ],
      radiOptions: [
        {
          label: '静态检查',
          value: 0,
        },
        {
          label: '动态检查',
          value: 1,
        },
      ],
      departs: [],
      checkType: 0,
      model: {
        skillLevelArr: []
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol1: {
        xs: { span: 12 },
        sm: { span: 10 },
      },
      wrapperCol1: {
        xs: { span: 12 },
        sm: { span: 14 },
      },
      labelCol2: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      confirmLoading: false,
      validatorRules: {
        deviceTypeId: [{ required: true, message: '请输入设备!' }],
        depard: [{ required: true, message: '请输入部件!' }],
        content: [{ required: true, message: '请输入检修要求!' }],
        repairRange: [{ required: true, message: '请输入修程!' }],
        mutualInspection: [{ required: true, message: '请输入互检!' }],
        personalizedInspection: [{ required: true, message: '请输入专检!' }],
        dispOrder: [{ required: true, message: '请输入序号!' }],
        // skillLevel: [{ required: true, message: '请选择最低技能级别!' }],
        skillLevelArr: [
          { required: true, type: 'array', min: 1, message: '请选择技能级别!' }
        ],
        inspection: [{ required: true, message: '请输入检查!' }],
      },
      url: {
        add: '/regular/regularDetail/add',
        edit: '/regular/regularDetail/edit',
        queryById: '/regular/regularDetail/queryById',
        listDeparts: '/device/part/list',
        listDeviceType:"/device/buDeviceType/list/all"
      },
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    changeCheckType(e) {
      console.log('radio1 checked', e);
      // console.log('radio1 checkedsss', this.model.checkType);
      // if(this.model.checkType === e){
      //   this.model.checkType = null;
      // }else {
      //   this.model.checkType = e;
      // }
    },
    changeMeasure(record) {
      this.model.measure = record === '0' ? '1' : '0'
    },
    convertToTreeSelect (data) {
      return data.map(item => {
        // 创建基本节点
        const node = {
          key: item.id,
          value: item.id,
          title: item.typeName
        };
        // 如果有子节点，递归处理
        if (item.subTypes && item.subTypes.length > 0) {
          node.children = this.convertToTreeSelect(item.subTypes);
        }
        return node;
      });
    },
    measureSelected(data) {
      console.log('measure', data)
      if (data.points.length > 0 && this.model.id) {
        httpAction(this.url.edit, {
          id: this.model.id, measure: '1'
        }, 'put').then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    },
    handleAddMeasure(detailId,deviceTypeId) {
      this.$refs.measureModal.show(detailId,deviceTypeId)
    },
    loadDeparts(id) {
      getAction(this.url.listDeviceType,{pid:id}).then((res) => {
        console.log('部件',res)
        if (res.success) {
          this.departs = this.convertToTreeSelect(res.result);
        } else {
          this.$message.error(res.message)
        }
      })
    },
    add(record) {
      this.modelDefault.deviceTypeId = record.deviceTypeId
      this.modelDefault.regularId = record.id
      this.modelDefault.rapairRange = record.rapairRange
      this.modelDefault.inspections = [0, 0]//专检、互检
      this.modelDefault.skillLevelArr = []
      this.modelDefault.measure = '0';
      this.loadDeparts(record.deviceTypeId)
      this.model = Object.assign({}, this.modelDefault)
    },
    edit(record) {
      this.modelDefault = record
      this.modelDefault.rapairRange = record.repairRange
      this.modelDefault.inspections = [record.personalizedInspection,record.mutualInspection]//专检、互检
      this.modelDefault.measure = record.measure
      // 字符串 → 数组
      if (record.skillLevel) {
        this.modelDefault.skillLevelArr = record.skillLevel.split(',')
      } else {
        this.modelDefault.skillLevelArr = []
      }
      this.loadDeparts(record.deviceTypeId)
      this.model = Object.assign({}, this.modelDefault)
      this.visible = true
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          if (this.model.inspections) {
            this.model.personalizedInspection = this.model.inspections[0] === 1 ? 1 : 0//专检
            this.model.mutualInspection =
              this.model.inspections[1] === 2 || this.model.inspections[0] === 2 ? 2 : 0//互检
          } else {
            this.model.personalizedInspection = 0//专检
            this.model.mutualInspection = 0//互检
          }
          this.model.repairRange = this.model.rapairRange
          // 多选技能级别处理
          if (Array.isArray(this.model.skillLevelArr)) {
            this.model.skillLevel = this.model.skillLevelArr.join(',')
          } else {
            this.model.skillLevel = ''
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
  },
}
</script>

