/*
 *@description:证件上件共用组件
 *@author: hudw
 *@date: 2022-03-14 10:40:55
*/

<template>
  <div>
    <a-modal ref="imgView" :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>

    <a-modal width="70%" v-model="sVisible" v-bind="modalConfig" :confirmLoading="confirmLoading" @ok="handleOk">
      <p-grid-form ref="grid" selfUpdate :onValuesChange="onValuesChange" :span="12" :labelCol="{ span: 6 }" :wrapperCol="{ span: 16 }" :items="items">
        <div v-if="currentData" class="clearfix" slot="temperatureVOList" style="margin: 0">
          <a-col v-for="item in currentData.temperatureVOList" :key="item.containerName"  :span="12">
            <p-form-item type="number"
                :labelCol="{ span:8 }"
                :wrapperCol="{ span: 16 }"
                :label="item.containerName">
                <div style="display:flex;align-items: center;">
              <p-input-number :placeholder="'请输入'+item.containerName" :min="-999999" v-model="item.temperature"  style="flex:1" /><span style="padding-left: 5px;">°c</span>
            </div>

            </p-form-item>
          </a-col>
        </div>
        <div class="clearfix" slot="photo3" style="margin: 0">
          <a-upload
            list-type="picture-card"
            :file-list="fileList3"
            accept="image/jpeg,image/png"
            @preview="handlePreview"
            :showUploadList="{ showRemoveIcon: false }"
          >
          </a-upload>
        </div>
        <div class="clearfix" slot="photo" style="margin: 0">
          <a-upload
            :remove="handleRemove"
            list-type="picture-card"
            :before-upload="beforeUpload"
            :file-list="fileList"
            accept="image/jpeg,image/png"
            @preview="handlePreview"
            :showUploadList="{ showRemoveIcon: view < 3 }"
            @change="handleChange"
          >
            <div v-if="view < 3 && fileList.length < count">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
        </div>
        <div v-if="isPhoto2" class="clearfix" slot="photo2" style="margin: 0">
          <a-upload
            :remove="handleRemove2"
            list-type="picture-card"
            :before-upload="beforeUpload2"
            :file-list="fileList2"
            accept="image/jpeg,image/png"
            @preview="handlePreview"
            :showUploadList="{ showRemoveIcon: view < 3 }"
            @change="handleChange2"
          >
            <div v-if="view < 3 && fileList2.length < count">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
        </div>
      </p-grid-form>

      <t-table
        ref="table"
        :customScrollbar="true"
        dragle
        bordered
        row-key="id"
        :scroll="{ x: true, y: 300 }"
        :columns="gridItems"
        :data-source.sync="gridDataSource"
        :rowSelectType="false"
        :pagination="false"
        v-if="modalTableShow"
      >
        <template slot="editPcs" slot-scope="text, record">
          <p-input-number v-model="record.editPcs" style="width: 100%" :min="0" :precision="0" @change="(value) => editPcsChange(value, record)"></p-input-number>
        </template>
      </t-table>
    </a-modal>
  </div>
</template>
<script>
import { setFormItems, updateImg, getPaperId } from './setConfig.js';
import { initDictionary } from '@/blocks/utils';
import { UPCLOUD_RDC_TMS_IMAGE_HOST } from '@/config/serviceSettings.js';
import store from '@/store';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      return resolve(reader.result);
    };
    reader.onerror = (error) => reject(error);
  });
}
let options = null;

export default {
  name: 'updateFormModal',
  props: {
    count: {
      type: Number,
      default: 4,
    },
    rowKey: {
      type: null,
      default: 'id',
    },
    setFilterValues: {
      type: Function,
    },
    onValuesChange: {
      type: Function,
    },
    /**0=不显示, 1=新建，2=修改 ，3=查看 */
    view: 0,
    title: '',
    visible: false,
    columns: [],
    targetKeys: [],
    currentData: null,
    imgFile: [],
    formItems: null,
    gridItems: [],
    gridDataSource: [],
    /**DELIVERY_HANDLE_TYPE=待送达, PICKUP_HANDLE_TYPE=待提货 */
    modalTableShow: false,
    //   {
    //   uid: '-1',
    //   name: 'image.png',
    //   status: 'done',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    // },
    //true:缓存数据跟主表一起保存，false:直接调接口保存提交
    btnSave: false, //直接调接口保存提交
  },

  computed: {
    isPhoto2() {
      return this.items?.some((item) => item?.scopedSlots?.customRender === 'photo2');
    },
    RELATION_THIRD_SYSTEM() {
      return this.$store.state?.sysParameter?.sysParameter_TMS?.RELATION_THIRD_SYSTEM?.value?.split(',') ?? [];
    },
    modalConfig() {
      const { title } = this;
      return { title, width: 740 };
    },
  },
  data() {
    return {
      options: options,
      confirmLoading: false,
      items: setFormItems(this, this.view),
      sVisible: this.visible,
      previewVisible: false,
      previewImage: '',
      cacheFile: [],
      cacheFile2: [],
      fileList: [],
      fileList2: [],
      fileList3: [],
      laterFileList: [], //之后新加入的
      laterFileList2: [], //之后新加入的
      basePicture: [],
      basePicture2: [],
      basePicture3: [],
    };
  },
  watch: {
    currentData(data) {
      if (data) {
        if (data.picture) {
          this.basePicture = data.picture.split(',');
        }
        if (data.picture2) {
          this.basePicture2 = data.picture2.split(',');
        }
        if (data.picUrls) {
          this.basePicture3 = data.picUrls.split(',');
        }
        this.form()?.setFieldsValue(data);
      }
    },
    visible(value) {
      this.sVisible = value;
    },

    sVisible(value) {
      this.cacheFile = [];
      this.fileList = [];
      this.cacheFile2 = [];
      this.fileList2 = [];
      this.confirmLoading = false;
      if (value && this.view > 0) {
        if (this.view === 1) {
          return getPaperId().then((res) => {
            if (res.success && res.data) {
              this.setFilterValues && this.setFilterValues(res.data);
              this.$refs.grid.form.setFieldsValue({ id: res.data });
            } else {
              this.$exception(res);
            }
          });
        }

        this.items = setFormItems(this, this.view);
        this.$nextTick(() => {
          this.$refs.grid.form.resetFields();
          this.fileList = this.basePicture.map((str, index) => {
            return {
              uid: index,
              name: str,
              status: 'done',
              url: UPCLOUD_RDC_TMS_IMAGE_HOST + '/' + str,
            };
          });
          this.fileList2 = this.basePicture2.map((str, index) => {
            return {
              uid: index,
              name: str,
              status: 'done',
              url: UPCLOUD_RDC_TMS_IMAGE_HOST + '/' + str,
            };
          });
          this.fileList3 = this.basePicture3.map((str, index) => {
            return {
              uid: index,
              name: str,
              status: 'done',
              url: UPCLOUD_RDC_TMS_IMAGE_HOST + '/' + str,
            };
          });

          if (this.view > 1 && this.currentData) {
            // //是否显示启运温度
            // if (this.currentData.showDepartureTemperature) {
            //   this.$refs.grid.form.unhiddenItem('departureTemperature');
            // } else {
            //   this.$refs.grid.form.hiddenItem('departureTemperature');
            // }
            if (this.RELATION_THIRD_SYSTEM.includes('1')) {
              //设备
              this.$refs.grid.form.unhiddenItem('vehicleDeviceName');
            } else {
              this.$refs.grid.form.hiddenItem('vehicleDeviceName');
            }
            //  //容器
            // if (this.RELATION_THIRD_SYSTEM.includes('2') || this.RELATION_THIRD_SYSTEM.includes('3')) {
            //   this.$refs.grid.form.unhiddenItem('containerName');

            // } else {
            //   this.$refs.grid.form.hiddenItem('containerName');
            // }

            this.setFilterValues && this.setFilterValues(this.currentData);
            this.$refs.grid.form.setFieldsValue(this.currentData);
          }
        });
      } else {
        this.$nextTick(() => {
          this.items = [];
        });
      }
      setTimeout(() => {
        this.$refs?.table?.resize()
      },200)
      this.$emit('update:visible', value);
    },
  },
  mounted() {
    console.log('scopedSlots', this.$scopedSlots);
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange(obj) {
      const { fileList, file } = obj;
      if (file.status == 'removed') {
        this.cacheFile = this.cacheFile.filter((item) => {
          return item.uid !== file.uid;
        });
      }
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        this.fileList = fileList;
      }
    },
    handleRemove(file) {
      this.basePicture = this.basePicture.filter((str) => {
        return str !== file.name;
      });
      this.fileList = this.fileList.filter((item) => {
        return item.name !== file.name;
      });
    },
    handleRemove2(file) {
      this.basePicture2 = this.basePicture2.filter((str) => {
        return str !== file.name;
      });
      this.fileList2 = this.fileList2.filter((item) => {
        return item.name !== file.name;
      });
    },
    beforeUpload(file, fileList) {
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        this.cacheFile.push(file);
      } else {
        this.$exception({
          message: '图片格式不正确，请上传.jpg/.png文件',
        });
      }
      return false;
    },
    beforeUpload2(file, fileList) {
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        this.cacheFile2.push(file);
      } else {
        this.$exception({
          message: '图片格式不正确，请上传.jpg/.png文件',
        });
      }
      return false;
    },
    handleChange2(obj) {
      const { fileList, file } = obj;
      if (file.status == 'removed') {
        this.cacheFile2 = this.cacheFile2.filter((item) => {
          return item.uid !== file.uid;
        });
      }
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        this.fileList2 = fileList;
      }
    },

    handleOk() {
      let _this = this;

      let grid = this.$refs.grid;
      this.$refs.grid.form.validateFields((errors, values) => {
        if (!errors) {
          let submit = async () => {
            let formData = new FormData();
            let size = 0;
            values.picture = _this.basePicture;
            if (_this.cacheFile.length === 0) {
              values.picture = values.picture.join();
              return values;
            }

            _this.cacheFile.forEach((file) => {
              size = +file.size;
              formData.append('file', file);
            });
            if (size > 31457280) {
              alert('文件上传过大');
            }
            formData.append('directory', '/tms');
            formData.append('storageType', 0);
            formData.append('isFileName', 0);
            _this.confirmLoading = true;
            return updateImg(this, formData)
              .then((response) => {
                if (response.success) {
                  let fileList = response.data.map((item) => {
                    const { id, path, fileName } = item;
                    return path;
                  });

                  if (values.picture.length > 0) {
                    values.picture = values.picture.concat(fileList);
                  } else {
                    values.picture = fileList;
                  }
                  values.picture = values.picture.join();
                  return values;
                } else {
                  _this.confirmLoading = false;
                  _this.$exception(response);
                  return null;
                }
              })
              .catch(() => {
                _this.confirmLoading = false;
                return null;
              });
          };

          if (grid.$slots.photo2) {
            let submit2 = async () => {
              let formData = new FormData();
              let size = 0;
              values.picture2 = _this.basePicture2;
              if (_this.cacheFile2.length === 0) {
                //没有加入新图片，就行list的数据返回
                values.picture2 = values.picture2.join();
                return values;
              }
              _this.cacheFile2.forEach((file) => {
                size = +file.size;
                formData.append('file', file);
              });
              if (size > 31457280) {
                alert('文件上传过大');
              }
              formData.append('directory', '/tms');
              formData.append('storageType', 0);
              formData.append('isFileName', 0);
              _this.confirmLoading = true;
              return updateImg(this, formData)
                .then((response) => {
                  if (response.success) {
                    let fileList = response.data.map((item) => {
                      const { id, path, fileName } = item;
                      return path;
                    });

                    if (values.picture.length > 0) {
                      values.picture2 = values.picture2.concat(fileList);
                    } else {
                      values.picture2 = fileList;
                    }
                    values.picture2 = values.picture2.join();

                    return values;
                  } else {
                    _this.confirmLoading = false;
                    _this.$exception(response);
                    return null;
                  }
                })
                .catch(() => {
                  _this.confirmLoading = false;
                  return null;
                });
            };
            _this.confirmLoading = true;
            return _this.$emit(
              'ok',
              [submit, submit2],
              () => {
                _this.confirmLoading = false;
              },
              { gridData: _this.gridDataSource }
            );
          }
          _this.confirmLoading = true;
          return _this.$emit(
            'ok',
            submit,
            () => {
              _this.confirmLoading = false;
            },
            { gridData: _this.gridDataSource }
          );
        }
      });
    },

    form() {
      return this.$refs?.grid?.form ?? null;
    },

    // 表格联动
    editPcsChange(value, record) {
      record.volume = parseFloat(this.BigJs(value || 0).times(record.unitVolume || 0));
      record.weight = parseFloat(this.BigJs(value || 0).times(record.unitWeight || 0));
    },
  },
};
</script>
<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>


