<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="设备编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['deviceCode',{rules: [{ required: true, message: '请输入设别编号!' }]}]" placeholder="请输入设备编号"  ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="设备类型" :labelCol="labelCol" :wrapperCol="wrapperCol" >
              <a-tree-select
                v-decorator="['deviceTypeId',{rules: [{ required: true, message: '请选择设备类型!' }]}]" :trigger-change="true"
                v-model="model.deviceTypeId"
                :tree-data="deviceTypes"
                placeholder="请选择设备类型"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="设备名称" :labelCol="labelCol" :wrapperCol="wrapperCol" >
              <a-input v-decorator="['deviceName',{rules: [{ required: true, message: '请输入设备名称!' }]}]" placeholder="请输入设备名称"  ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="规格型号" :labelCol="labelCol" :wrapperCol="wrapperCol" >
              <a-input v-decorator="['typeId',{rules: [{ required: true, message: '请输入规格型号!' }]}]" placeholder="请输入规格型号"  ></a-input>
            </a-form-item>
          </a-col>
<!--          <a-col :span="24">-->
<!--            <a-form-item label="运行状态" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <j-dict-select-tag placeholder="请选择运行状态" dictCode="device_use" :triggerChange="true"-->
<!--                v-decorator="['deviceUse']"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24">-->
<!--            <a-form-item label="使用状态" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <j-dict-select-tag placeholder="请选择使用状态" dictCode="use_status" :trigger-change="true"-->
<!--                                 v-decorator="['useStatus']"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24">-->
<!--            <a-form-item label="设备状态" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <j-dict-select-tag placeholder="请选择设备状态" dictCode="device_status" :trigger-change="true"-->
<!--                 v-decorator="['deviceStatus']"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24">-->
<!--            <a-form-item label="状态改变原因" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <a-input v-decorator="['statusChange']" placeholder="请输入状态改变原因" allow-clear ></a-input>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :span="24">
            <a-form-item label="设备用途" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['usageId']" placeholder="请输入设备用途" allow-clear ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="安装时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择安装时间" v-decorator="['setupTime']" :trigger-change="true" style="width: 100%" />
            </a-form-item>
          </a-col>
<!--          <a-col :span="24">-->
<!--              <a-form-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--                <j-select-user-by-dep v-model="directorId" placeholder="请选择负责人" :multi="false"-->
<!--                                      dictCode="sys_user,realname,username"/>-->
<!--              </a-form-item>-->
<!--          </a-col>-->
          <a-col :span="24">
            <a-form-item label="包机人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-user-by-dep v-decorator="['userJi']" placeholder="请选择包机人" :multi="false"
                                    dictCode="sys_user,realname,username"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
          <a-form-item label="包修人" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-select-user-by-dep v-decorator="['userXiu']" placeholder="请选择包修人" :multi="false"
                                  dictCode="sys_user,realname,username"/>
          </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag v-decorator="['supplierId']" :trigger-change="true" placeholder="请选择供应商"
                                 dictCode="bu_supplier,name,id"></j-dict-select-tag>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="安装地点" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-tree-select
                v-decorator="['location']" :trigger-change="true"
                v-model="model.location"
                :tree-data="deviceLocations"
                placeholder="请选择安装地点"
                tree-default-expand-all
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="启用时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择启用时间" v-decorator="['enableTime']" :trigger-change="true" style="width: 100%" />
            </a-form-item>
          </a-col>
<!--          <a-form-model-item label="头像" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--            <j-image-upload class="avatar-uploader" text="上传" v-model="model.avatar" ></j-image-upload>-->
<!--          </a-form-model-item>-->
          <a-col :span="24">
            <a-form-item label="图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload class="avatar-uploader" v-decorator="['img']" :isMultiple="false"></j-image-upload>
            </a-form-item>
          </a-col>
<!--          <a-col :span="8">-->
<!--            <a-form-item label="二维码" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <j-image-upload v-decorator="['code']" :isMultiple="false"></j-image-upload>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDate from '@/components/jeecg/JDate'
  import JSelectUserByDep from '@comp/jeecgbiz/JSelectUserByDep'
  import JImageUpload from '@comp/jeecg/JImageUpload'
  import JSelectMultiUser from '@comp/jeecgbiz/JSelectMultiUser'

  export default {
    name: 'BuDeviceForm',
    components: {
      JSelectMultiUser,
      JSelectUserByDep,
      JFormContainer,
      JImageUpload,
      JDate,
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
        },
        url: {
          add: "/device/buDevice/add",
          edit: "/device/buDevice/edit",
          queryById: "/device/buDevice/queryById",
          listDeviceType:"/device/buDeviceType/list/deviceType",
          listDeviceLocation:"/device/deviceLocation/list/all"
        },
        directorId:"",
        deviceTypes:[],
        deviceLocations:[],
      }
    },
    default: {
      name: '用户',
      width: 1200,
      displayKey: 'realname',
      returnKeys: ['id', 'realname'],
      queryParamText: '账号',
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
      // 加载设备类别树形表
      this.loadAllDeviceType();
      this.loadAllDeviceLocation();
    },
    methods: {
      convertToTreeSelect (data) {
        return data.map(item => {
          const title = item.typeName || item.title || '未知标题';
          // 创建基本节点
          const node = {
            key: item.id,
            value: item.id,
            title: title
          };
          // 如果有子节点，递归处理
          if (item.subTypes && item.subTypes.length > 0) {
            node.children = this.convertToTreeSelect(item.subTypes);
          }
          return node;
        });
      },
      loadAllDeviceType() {
        getAction(this.url.listDeviceType).then((res) => {
          if (res.success) {
            this.deviceTypes = this.convertToTreeSelect(res.result)
          } else {
            this.$message.error(res.message)
          }
        })
      },
      loadAllDeviceLocation() {
        getAction(this.url.listDeviceLocation, {}).then((res) => {
          if (res.success) {
            this.deviceLocations = this.convertToTreeSelect(res.result)
          } else {
            this.$message.error(res.message)
          }
        })
      },
      add () {
        this.edit({});
      },
      getFormFieldValue(field){
        return this.form.getFieldValue(field)
      },
      edit (record) {
        console.log(record);
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.directorId = record.directorId;
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'deviceCode','deviceTypeId','deviceName','typeId','usageId','setupTime',
            'directorId','supplierId','location','enableTime','code','img','repairLine','ratedPower','userJi','userXiu','deviceToken'))
        })
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            formData.directorId = this.directorId;
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'deviceCode','deviceTypeId','deviceName','typeId','usageId','setupTime',
            'directorId','supplierId','location','enableTime','code','img','repairLine'))
      },
    }
  }
</script>