<template>
  <div class="approval-dialog">
    <div id="approvalModalBox"></div>
    <a-modal
      class="approval-out-dialog"
      v-if="props.approvalVisiable"
      v-model:visible="props.approvalVisiable"
      @ok="handleOk"
      @cancel="handleOk"
      :getContainer="getContainer">
      <template #title>
        <div class="title">新建审批</div>
      </template>
      <template #closeIcon> <img src="@/assets/image/approval/close.png" /></template>
      <a-form class="form-dialog" ref="addForm" :model="formState" name="basic" autocomplete="off" labelAlign="left" :labelCol="state.labelCol">
        <a-form-item :colon="false" label="提交人" name="username">{{ Local.get("userInfo").NickName || "" }} </a-form-item>
        <a-form-item v-show="state.ApprovalUsers.length > 0" :colon="false" label="审核人" name="username">
          <a-timeline style="margin-top: 10px">
            <a-timeline-item v-for="(item, index) in state.ApprovalUsers" :key="index">{{ item.Name }}</a-timeline-item>
          </a-timeline>
        </a-form-item>
        <a-form-item v-show="state.CopyUsers" :colon="false" label="抄送人" name="username">{{ state.CopyUsers }} </a-form-item>
        <a-form-item
          v-show="
            formState.Type === 'bundle' || formState.Type === 'work' || formState.Type === 'exhibition' || formState.Type === 'artExhibitionReward'
          "
          :colon="false"
          label="领取时间"
          name="ReceivedAt">
          <a-date-picker v-model:value="formState.ReceivedAt" valueFormat="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item v-show="formState.Type === 'exhibition'" :colon="false" label="申请数量" name="username"
          >{{ formState.packageNum }}
        </a-form-item>
        <a-space
          v-if="formState.Type === 'exhibition' || formState.Type === 'artExhibitionReward'"
          class="space"
          v-for="(item, index) in formState.exhibition"
          :key="item.id">
          <a-form-item
            :name="['exhibition', index, 'ShowDate']"
            :label="'画展时间'"
            :rules="[
              {
                required: formState.Type === 'exhibition' ? true : false,
                trigger: 'blur',
                message: '请填写画展时间',
              },
            ]">
            <a-date-picker
              :disabled="formState.Type === 'artExhibitionReward' ? true : false"
              v-model:value="item.ShowDate"
              show-time
              format="YYYY-MM-DD HH:mm"
              :show-time="{ format: 'HH:mm' }"
              valueFormat="YYYY-MM-DD HH:mm" />
          </a-form-item>
          <a-form-item
            :name="['exhibition', index, 'Address']"
            :label="'画展地址'"
            :rules="[
              {
                required: formState.Type === 'exhibition' ? true : false,
                trigger: 'blur',
                message: '请选填写画展地址',
              },
            ]">
            <a-select
              :disabled="formState.Type === 'artExhibitionReward' ? true : false"
              v-if="formState.Type === 'exhibition' || formState.Type === 'artExhibitionReward'"
              show-search
              :filter-option="filterOption"
              v-model:value="item.Address"
              style="width: 120px"
              :options="state.addressOpt"></a-select>
          </a-form-item>
          <a-form-item :name="['exhibition', index, 'PackageID']" :label="'名称' + (index + 1)">
            <a-select
              ref="exSelect"
              dropdownClassName="drop-down"
              v-model:value="item.PackageID"
              style="width: 190px"
              show-search
              :filter-option="filterOption"
              option-label-prop="label"
              @change="(value, label) => handleChange(value, label, item)">
              <a-select-option v-for="item in state.exhibitionList" :key="item.ShowUID" :value="item.ShowUID" :label="item.ShowName"
                ><div style="width: 257px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; display: inline-flex; text-align: center">
                  {{ item.ShowName }}&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp{{ item.ArtworkNum }}
                </div>
                &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                <!-- <a @click="checkArtShow(item)">查看详情</a> -->
              </a-select-option>
            </a-select>
          </a-form-item>
          <div>
            <span style="margin-right: 20px">画家名称：{{ item.artExhibitionDetail.ArtistName }}</span>
            <span style="margin-right: 20px">包含画作数量：{{ item.artExhibitionDetail.ArtworkNum }}</span>
            <span style="margin-right: 20px">包含画作总平尺：{{ item.artExhibitionDetail.Ruler }}</span>
            <span>画展包总价：{{ item.totalPrice }}</span>
          </div>
          <a-form-item label="">
            <a-table
              class="artwork-table"
              :rowKey="(record) => record.ArtworkUuid"
              :columns="state.ArtworksColoums"
              :data-source="item.Artworks"
              :scroll="{ y: 325 }"
              :pagination="false">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'SmallPic'">
                  <!-- 展示图片的优先级为DigiArtImg，HdPic，PhotoPic -->

                  <a-image
                    style="height: 40px; width: 40px"
                    :preview="{
                      src: record.SmallPic,
                    }"
                    :src="record.SmallPic + '?x-oss-process=image/resize,w_158,h_158'" />
                </template>
                <template v-if="column.key === 'Reward'">
                  <a-input :disabled="formState.Type === 'exhibition'" v-model:value="record.Reward" @change="countTotalPrice($event, item)" />
                </template>
                <template v-if="column.key === 'oneAllPrice'">
                  {{ record.Reward * record.Ruler }}
                </template>
                <template v-if="column.key === 'SaleAddress'">
                  <a-select
                    :disabled="formState.Type === 'artExhibitionReward'"
                    v-model:value="record.SaleAddress"
                    :options="state.childAddressOpt"
                    show-search
                    :filter-option="filterOption"
                    @change="(value, selectedOptions) => handleAddressChange(value, selectedOptions, record)" />
                </template>
              </template> </a-table
            ><MinusCircleOutlined style="margin-left: 10px" @click="removeExhibiton(item)"
          /></a-form-item>
        </a-space>
        <a-form-item v-show="formState.Type === 'exhibition' || formState.Type === 'artExhibitionReward'">
          <a-button class="save-btn" @click="addExhibition(formState.Type === 'artExhibitionReward' ? true : false)"> 添加画展包 </a-button>
        </a-form-item>
        <!-- <a-form-item
          v-if="formState.Type === 'work'"
          style="margin-left: 454px"
          :colon="false"
          label=""
        >

        </a-form-item> -->
        <div class="tags" v-if="formState.Type === 'work'">
          <span style="margin-left: 15px" v-for="item in state.selectedRows"
            ><close-circle-outlined @click="closeTag(item)" />{{ item.ArtworkName }}</span
          >
        </div>
        <a-form-item :colon="false" label="申请内容" name="workContent" v-if="formState.Type === 'work'">
          <div class="action-table">
            <div>
              <span style="font-size: 16px; margin-right: 10px">请选择画家画作</span>
              <a-select
                v-model:value="state.ArtistUID"
                show-search
                style="width: 150px; margin-right: 10px"
                :getPopupContainer="getContainer"
                placeholder="可搜索"
                :fieldNames="{ label: 'nameWithTnum', value: 'Uid' }"
                :options="state.options"
                :filter-option="aritstFilterOption"
                @change="handleAritstChange"></a-select>
            </div>
            <a-switch
              v-model:checked="giveChecked"
              @change="
                (val) => {
                  val ? getWorkList(1) : getWorkList(-1);
                }
              "
              checked-children="可分配画作"
              un-checked-children="全部画作" />
          </div>

          <a-table
            class="artwork-table"
            :rowKey="(record) => record.Id"
            :columns="state.workColumns"
            :row-selection="{
              onChange: onSelectChange,
              selectedRowKeys: state.selectedRowKeys,
              checkStrictly: false,
              getCheckboxProps: (record) => ({
                disabled: !(record.StorageStatus === 1 && record.SaleStatus < 6),
              }),
            }"
            :data-source="state.workTableData"
            :scroll="{ y: 245 }"
            :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'HdPic'">
                <img style="height: 40px; width: 40px" :src="record.HdPic + '?x-oss-process=image/resize,w_40,h_40'" />
              </template>
            </template>
          </a-table>
        </a-form-item>
        <a-form-item
          v-if="formState.Type === 'bundle'"
          :colon="false"
          :rules="[{ required: true, trigger: 'blur', message: '请选填写数量' }]"
          label="申请数量"
          name="ApplicationsNum"
          ><a-input class="count-input" :bordered="false" style="width: 140px" v-model:value="formState.ApplicationsNum" placeholder="" />
        </a-form-item>
        <div>
          <a-form-item :colon="false" label="审核类型" name="Type" :rules="[{ required: true, trigger: 'blur', message: '请选择审核类型' }]"
            ><a-select ref="select" :bordered="false" v-model:value="formState.Type" style="width: 140px" @change="changeType">
              <a-select-opt-group v-for="item in aprovalTypeOpt" :label="item.Title">
                <a-select-option v-for="row in item.List" :key="row.ID" :value="row.KeyWord">{{ row.Title }}</a-select-option>
              </a-select-opt-group>
            </a-select>
          </a-form-item>

          <div v-if="formState.Type === 'bundlePayPrice'">
            <a-form-item name="pricePackageID" :label="'画展包选择'">
              <a-select
                ref="exSelect"
                dropdownClassName="drop-down"
                v-model:value="formState.pricePackageID"
                style="width: 190px"
                option-label-prop="label"
                show-search
                :filter-option="filterOption"
                @change="handlePriceChange">
                <a-select-option v-for="item in state.exhibitionList" :key="item.ShowUID" :value="item.ShowUID" :label="item.ShowName"
                  ><div
                    style="width: 257px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; display: inline-flex; text-align: center">
                    {{ item.ShowName }}
                  </div>
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item :colon="false" label="画家名称" name="ArtistName">{{ formState.pricePackageInfo?.ArtistName }}</a-form-item>
            <a-form-item :colon="false" label="画展包底价" name="Price">{{ formState.pricePackageInfo?.Price }}</a-form-item>
            <a-form-item :colon="false" label="画作数量" name="ArtworkNum">{{ formState.pricePackageInfo?.ArtworkNum }}</a-form-item>
            <a-form-item :colon="false" label="画作总平尺数" name="Ruler">{{ formState.pricePackageInfo?.Ruler }}</a-form-item>
            <a-form-item :colon="false" label="画展时间" name="ShowTime">{{ formState.pricePackageInfo?.ShowTime }}</a-form-item>
            <a-form-item :colon="false" label="画展地点" name="Address">{{ formState.pricePackageInfo?.Address }}</a-form-item>
          </div>
          <a-space v-show="formState.isDiy" class="space" v-for="(item, index) in state.editList" :key="index">
            <a-form-item style="overflow: auto" :name="['item', index, 'ApprovalName']" :label="item.ApprovalName">
              <a-input v-if="item.ApprovalType === 'string'" style="width: 100%" v-model:value="item.ApprovalValue" placeholder="" />
              <a-date-picker v-if="item.ApprovalType === 'date'" v-model:value="item.ApprovalValue" valueFormat="YYYY-MM-DD" />
              <fl-form-item
                v-if="item.ApprovalType === 'upload'"
                type="mulupload"
                pageType="edit"
                field="ApprovalValue"
                height="100px"
                :otherParams="{
                  source: 'approval',
                  mask: '',
                  otherFileType: null,
                  type: 'all',
                }"
                :val="item.ApprovalValue"
                uploadTitle=""
                @triggerValChange="(val, field) => handleValChange(val, field, index)" />
              <div v-if="item.ApprovalType === 'artworkList'" class="artTable">
                <div class="action-table">
                  <div>
                    <span style="font-size: 16px; margin-right: 10px">请选择画家画作</span>
                    <a-select
                      v-model:value="state.ArtistUID"
                      show-search
                      style="width: 150px; margin-right: 10px"
                      :getPopupContainer="getContainer"
                      placeholder="可搜索"
                      :fieldNames="{ label: 'nameWithTnum', value: 'Uid' }"
                      :options="state.options"
                      :filter-option="aritstFilterOption"
                      @change="handleAritstChange"></a-select>
                  </div>
                </div>

                <a-table
                  class="artwork-table"
                  :rowKey="(record) => record.Id"
                  :columns="state.workColumns"
                  :row-selection="{
                    onChange: onSelectChange,
                    selectedRowKeys: state.selectedRowKeys,
                    checkStrictly: false,
                  }"
                  :data-source="state.workTableData"
                  :scroll="{ y: 245 }"
                  :pagination="false">
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'HdPic'">
                      <img style="height: 40px; width: 40px" :src="record.HdPic + '?x-oss-process=image/resize,w_40,h_40'" />
                    </template>
                  </template>
                </a-table>
              </div>
            </a-form-item>
          </a-space>
          <a-form-item :colon="false" label="具体内容" name="Content" v-show="!formState.isDiy">
            <a-textarea class="textarea" v-model:value="formState.Content" placeholder="在此输入具体内容" :rows="4" />
          </a-form-item>
        </div>
      </a-form>
      <template #footer>
        <div class="button-group">
          <a-button @click="handleOk" class="cancel-btn">取消</a-button>
          <a-button @click="save" class="save-btn">提交</a-button>
        </div>
      </template>
    </a-modal>
  </div>
  <CreateExhibition
    :createExVisible="createExVisible"
    @createHandleOk="createHandleOk"
    :type="'detail'"
    :title="'查看画展包'"
    :isApproval="true"
    :rowData="state.rowData" />
</template>

<script setup>
import { ref, reactive, watch, onMounted, defineProps, defineEmits, getCurrentInstance, nextTick } from "vue";
import { CloseCircleOutlined, MinusCircleOutlined } from "@ant-design/icons-vue";
import { processError, processSuccess, processWarning } from "@/utils/helper/message";
import flFormItem from "@/components/layout/form/formItem.vue";
import { Local } from "@/utils/storage.js";
import CreateExhibition from "@/views/artExhibition/components/createExhibition.vue";
const currentInstance = getCurrentInstance();
const { $request } = currentInstance.appContext.config.globalProperties;
const formState = reactive({
  Type: "",
  Content: "",
  ApplicationsNum: null,
  packageNum: 0,
  ReceivedAt: "",
  pricePackageID: "",
  pricePackageInfo: {},
  exhibition: [
    {
      Address: "",
      ShowDate: "",
      PackageID: "",
      PackageName: "",
      artExhibitionDetail: {},
      id: Date.now(),
      Artworks: [],
    },
  ],
  isDiy: false,
  CustomizeInfo: [],
});
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 14 },
};
const giveChecked = ref(false);
const addForm = ref();
const state = reactive({
  childAddressOpt: [],
  editList: [],
  rowData: {},
  SaleAddressOpt: [],
  addressOpt: [],
  ArtistName: "",
  ArtistUID: "",
  options: [],
  workColumns: [
    {
      title: "画作名称",
      dataIndex: "ArtworkName",
      align: "center",
    },
    {
      title: "画家名称",
      dataIndex: "ArtistName",
      align: "center",
    },
    {
      title: "图片",
      dataIndex: "HdPic",
      align: "center",
      key: "HdPic",
    },
    {
      title: "库存状态",
      dataIndex: "storageTxt",
      align: "center",
    },
    {
      title: "销售状态",
      dataIndex: "saleTxt",
      align: "center",
    },
  ],
  ArtworksColoums: [
    {
      title: "画作编号",
      dataIndex: "Tfnum",
      width: 100,
      align: "center",
      sorter: {
        compare: (a, b) => {
          let a1 = a.Tfnum;
          let b1 = b.Tfnum;

          console.log(a1, b1);
          if (a1 < b1) {
            return -1;
          }
          if (a1 > b1) {
            return 1;
          }
          if (a1 == b1) {
            return 0;
          }
        },
      },
    },
    {
      title: "小图",
      dataIndex: "SmallPic",
      width: 100,
      align: "center",
      key: "SmallPic",
    },
    {
      title: "画作名称",
      dataIndex: "ArtworkName",
      width: 100,
      align: "center",
    },

    {
      title: "长度",
      dataIndex: "Length",
      width: 100,
      align: "center",
    },
    {
      title: "宽度",
      dataIndex: "Width",
      width: 100,
      align: "center",
    },
    {
      title: "平尺数",
      dataIndex: "Ruler",
      width: 100,
      align: "center",
    },
    {
      title: "润格",
      dataIndex: "Reward",
      width: 140,
      align: "center",
      key: "Reward",
    },
    {
      title: "单幅总价",
      dataIndex: "oneAllPrice",
      width: 140,
      align: "center",
      key: "oneAllPrice",
    },
    {
      title: "销售站点",
      dataIndex: "SaleAddress",
      width: 190,
      align: "center",
      key: "SaleAddress",
    },
  ],
  exhibitionList: [],
  workTableData: [],
  selectedRowKeys: [],
  selectedRows: [],
  ApprovalUsers: [],
  CopyUsers: null,
  saleDict: {
    0: "未入库",
    1: "仓库",
    2: "数字化中",
    3: "鉴证中",
    4: "数字化已完成",
    5: "鉴证已完成",
    6: "待销售",
    7: "出库",
    8: "已售",
    9: "泰丰仓库"
  },
  storageDict: { 0: "未入库", 1: "仓库", 2: "数字化", 3: "鉴证" },
  hasRepeat: false,
});
// 生成画展包弹窗
const createExVisible = ref(false);
// 生成画展关闭回调
const createHandleOk = () => {
  createExVisible.value = false;
};
const props = defineProps({
  // 抄送人弹窗显示
  approvalVisiable: {
    type: Boolean,
    default: false,
  },
});
const handleValChange = (val, field, idx) => {
  state.editList[idx].ApprovalValue = val;
  console.log(state.editList);
};
// 获取二级地址
const loadData = async (value, label, item) => {};
// 获取销售地址
const getSaleAddress = async (ParentName = "") => {
  const res = await $request.HTTP.approval
    .getSaleAddress({ ParentName: ParentName })
    .then((res) => {
      if (res.status === 0) {
        if (ParentName) {
          state.childAddressOpt = res.data.map((item) => {
            return {
              value: item.Address,
              label: item.Address,
              id: item.StoreID,
            };
          });
        } else {
          state.addressOpt = res.data.map((item) => {
            return {
              value: item.Address,
              label: item.Address,
            };
          });
        }
      } else {
        processError(res.msg);
      }
    })
    .catch((e) => {});
};
// 选择地址回调
const handleAddressChange = (value, selectedOptions, record) => {
  console.log(value, selectedOptions, record);
  record.SaleAddressID = selectedOptions.id;
};

// 添加画展包
const addExhibition = (isReward) => {
  if (!isReward && formState.exhibition.length >= formState.packageNum) {
    processWarning("已超出最大申请数量");
    return;
  }
  formState.exhibition.push({
    Address: "",
    ShowDate: "",
    PackageID: "",
    PackageName: "",
    Artworks: [],
    artExhibitionDetail: {},
    id: Date.now(),
  });
};
// 删除画展包
const removeExhibiton = (item) => {
  let index = formState.exhibition.indexOf(item);
  if (index !== -1) {
    formState.exhibition.splice(index, 1);
  }
};
const handleAritstChange = (val, opt) => {
  state.ArtistName = opt.Uid;
  nextTick(() => {
    state.selectedRows = [];
    state.selectedRowKeys = [];
  });
  getWorkList();
};
const filterOption = (input, option) => {
  console.log(input, option);
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const aritstFilterOption = (input, option) => {
  return option.Name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
// 选中
const onSelectChange = (selectedRowKeys, rows) => {
  state.selectedRows = rows;
  state.selectedRowKeys = selectedRowKeys;
};
// 关闭
const closeTag = (tag) => {
  const id = JSON.parse(JSON.stringify(tag.Id));
  const tags = state.selectedRowKeys.filter((item) => item != id);
  const rows = state.selectedRows.filter((item) => item.Id != id);
  nextTick(() => {
    state.selectedRows = rows;
    state.selectedRowKeys = tags;
  });
};
const aprovalTypeOpt = ref([]);
// 获取审核类型
const getTpye = () => {
  $request.HTTP.approval
    .gruopAll({ page: 1, pageSize: 99999 })
    .then((res) => {
      if (res.status === 0) {
        aprovalTypeOpt.value = res.data.Data;
      } else {
        processError(res.msg);
      }
    })
    .catch((e) => {});
};
// 计算画展包总价
const countTotalPrice = (event, item) => {
  item.totalPrice = item.Artworks.reduce((acc, artwork) => {
    return acc + artwork.Ruler * parseInt(artwork.Reward || 0);
  }, 0);
};
// 获取画展包数量
const getPackageNum = () => {
  $request.HTTP.approval
    .getPackageNum({})
    .then((res) => {
      if (res.status === 0) {
        formState.packageNum = res.data.total || 0;
      } else {
        processError(res.msg);
      }
    })
    .catch((e) => {});
};
// 查看画展包详情
const checkArtShow = (val) => {
  state.rowData = val;
  createExVisible.value = true;
};
// 获取画展包详情
const getExDetail = async (val) => {
  return await $request.HTTP.artExhibition
    .artShowList({ ShowUID: val })
    .then((res) => {
      if (res.status == 0) {
        return res.data.data;
      } else {
        return [];
      }
    })
    .catch((e) => {});
};
// 审核类型切换
const changeType = () => {
  // 清空表单内容

  $request.HTTP.approval
    .getUsers({ KeyWord: formState.Type })
    .then((res) => {
      if (res.status === 0) {
        state.CopyUsers = res.data.CopyUsers
          ? res.data.CopyUsers.map((v) => {
              return v.Name;
            }).join(",")
          : null;
        state.ApprovalUsers = res.data.ApprovalUsers || [];

        if (res.data.IsCustom === 1) {
          formState.isDiy = true;
          getArtistList();
          state.editList = res.data.CustomizeInfo;
        } else {
          formState.isDiy = false;
          state.editList = [];
        }
      } else {
        processError(res.msg);
      }
    })
    .catch((e) => {});
  if (formState.Type === "work") {
    state.selectedRows = [];
    state.selectedRowKeys = [];
    // getWorkList();
    getArtistList();
  } else if (formState.Type === "exhibition") {
    getPackageNum();
    getExhibitionList();
    getSaleAddress();
    getSaleAddress("-1");
    formState.exhibition = [
      {
        Address: "",
        ShowDate: "",
        PackageID: "",
        PackageName: "",
        artExhibitionDetail: {},
        id: Date.now(),
        Artworks: [],
      },
    ];
  } else if (formState.Type === "artExhibitionReward") {
    getPackageNum();
    getExhibitionList([3]);

    formState.exhibition = [
      {
        Address: "",
        ShowDate: "",
        PackageID: "",
        PackageName: "",
        artExhibitionDetail: {},
        id: Date.now(),
        Artworks: [],
      },
    ];
  } else if (formState.Type === "bundlePayPrice") {
    getExhibitionList([4]);
  }
};
// 获取画家列表
const getArtistList = () => {
  $request.HTTP.artist
    .artistBaseInfoList({ Keyword: "", Page: 1, PageSize: 99999999 })
    .then((res) => {
      if (res.status == 0) {
        // 将Name和Tnum放入options
        const options = res.data.Data.map((v) => ({ ...v, nameWithTnum: v.Name + "(" + v.Tnum + ")" }));
        state.options = options;
      } else {
      }
    })
    .catch((e) => {});
};
// 获取画展包
const getExhibitionList = (val = [2]) => {
  let params = {
    Page: 1,
    PageSize: 99999,
    IsShow: val,
  };
  let res = $request.HTTP.artExhibition.artExListWithRel(params).then(
    (res) => {
      if (res.status === 0) {
        state.exhibitionList = res.data.Data;
      } else {
        processError(res.message || "获取数据失败");
      }
    },
    (err) => {
      processError(err.response.data.msg || "获取数据失败");
    }
  );
};
// 获取画作
const getWorkList = (StorageStatus = -1) => {
  $request.HTTP.artwork
    .artworkList({
      ArtistUID: state.ArtistUID,
      page: 1,
      pageSize: 99999,
      StorageStatus: StorageStatus,
    })
    .then((res) => {
      if (res.status === 0) {
        state.workTableData = res.data.Data;
        state.workTableData.forEach((v) => {
          v.storageTxt = state.storageDict[v.StorageStatus];
          v.saleTxt = state.saleDict[v.SaleStatus];
        });
      } else {
        processError(res.msg);
      }
    })
    .catch((e) => {});
};
// q:可以帮我优化下面这个save方法吗
const save = () => {
  addForm.value
    .validate()
    .then(() => {
      console.log(123);
      let data = {};
      if (formState.Type == "bundle") {
        data = {
          Type: formState.Type,
          Content: formState.Content,
          Bundle: {
            ApplicationsNum: parseInt(formState.ApplicationsNum),
            ReceivedAt: formState.ReceivedAt,
          },
        };
      } else if (formState.Type == "work") {
        if (state.selectedRows.length < 1) {
          processWarning("请至少选择一副画作");
          return;
        }
        let ApprovalWorks = [];
        state.selectedRows.forEach((v) => {
          ApprovalWorks.push({
            ArtworkName: v.ArtworkName,
            ArtworkID: v.Id,
            ArtistName: v.ArtistName,
            ArtworkCover: v.HdPic,
            ArtworkNumber: parseInt(v.Num),
            ArtistUID: state.ArtistUID,
          });
        });
        data = {
          Type: formState.Type,
          Content: formState.Content,
          Work: {
            ApprovalWorks: ApprovalWorks,
            ReceivedAt: formState.ReceivedAt,
          },
        };
      } else if (formState.Type == "exhibition" || formState.Type == "artExhibitionReward") {
        if (state.hasRepeat) {
          processWarning("请不要选择重复画作");
          return;
        }
        // 如果是画展包类型，没有销售地点则不让提交

        if (formState.Type === "exhibition") {
          const invalidArtworks = formState.exhibition.flatMap((element) => element.Artworks).filter((v) => !v.SaleAddress);
          if (invalidArtworks.length) {
            processWarning("销售地点为空");
            return;
          }
        }
        // 如果是画展包润格类型，没有润格不让提交
        if (formState.Type === "artExhibitionReward") {
          const invalidArtworks = formState.exhibition.flatMap((element) => element.Artworks).filter((v) => !v.Reward);
          if (invalidArtworks.length) {
            processWarning("润格为空");
            return;
          }
        }
        data = {
          Type: formState.Type,
          Content: formState.Content,
          Exhibition: {
            ApprovalExhibitions: formState.exhibition,
            ReceivedAt: formState.ReceivedAt,
          },
        };
      } else if (formState.Type == "bundlePayPrice") {
        // 如果没有画展时间和画展地点则不让提交
        if (!formState.pricePackageInfo.ShowTime || !formState.pricePackageInfo.Address) {
          processWarning("画展时间或画展地址为空");
          return;
        }
        data = {
          Type: formState.Type,
          BundlePayPrice: {
            ShowUid: formState.pricePackageInfo.ShowUID,
            ShowName: formState.pricePackageInfo.ShowName,
            ReceivedAt: formState.ReceivedAt,
            ShowDate: formState.pricePackageInfo.ShowTime,
            ShowLowPrice: formState.pricePackageInfo.Price + "",
            ArtworkNum: formState.pricePackageInfo.ArtworkNum,
            ArtworkSize: formState.pricePackageInfo.Ruler + "",
            ShowAddress: formState.pricePackageInfo.Address,
            ArtistName: formState.pricePackageInfo.ArtistName,
          },
        };
      } else {
        let artWorkJson = {};
        if (state.selectedRows) {
          artWorkJson = {
            Artworks: state.selectedRows,

            ArtistUID: state.ArtistUID,
          };
        }
        let temp = [];
        state.editList.forEach((v) => {
          temp.push({
            ApprovalValue:
              v.ApprovalType === "upload"
                ? JSON.stringify(v.ApprovalValue)
                : v.ApprovalType === "artworkList"
                ? JSON.stringify(artWorkJson)
                : v.ApprovalValue,
            ApprovalKey: v.ApprovalKey,
            ApprovalName: v.ApprovalName,
            ApprovalType: v.ApprovalType,
            ApprovalMark: v.ApprovalMark,
          });
        });
        data = { Type: formState.Type, CustomizeInfo: temp };
      }
      console.log(data);
      $request.HTTP.approval
        .cteateApproval(data)
        .then((res) => {
          if (res.status === 0) {
            handleOk();
            reset();
            processSuccess("新建成功");
          } else {
            processError(res.msg);
          }
        })
        .catch((e) => {});
    })
    .catch((error) => {});
};

// 重置
const reset = () => {
  addForm.value.resetFields();
};
const emit = defineEmits(["approvalHandleOk"]);
// 改变modal根节点 解决打开后出现padding
const getContainer = () => {
  return document.getElementById("approvalModalBox");
};
// 关闭回调
const handleOk = (e) => {
  emit("approvalHandleOk");
};
// 选项回调
const handleChange = async (value, label, item) => {
  let ids = [];
  formState.exhibition.forEach((v) => {
    ids.push(v.PackageID);
    if (v.PackageID === value) {
      v.PackageName = label.label;
    }
  });
  item.artExhibitionDetail = state.exhibitionList.find((v) => v.ShowUID === value);
  // 如果是画展包审批
  if (formState.Type === "artExhibitionReward") {
    item.Address = item.artExhibitionDetail.Address;
    item.ShowDate = item.artExhibitionDetail.ShowTime;
  }
  item.Artworks = await getExDetail(value);
  console.log(item);
  if (new Set(ids.map((item) => item)).size < ids.length) {
    processWarning("请不要选择重复画作");
    state.hasRepeat = true;
  } else {
    state.hasRepeat = false;
  }
};
// 价格单选项回调
const handlePriceChange = (value, label) => {
  // 找出value对应的画展包
  formState.pricePackageInfo = state.exhibitionList.find((v) => v.ShowUID === value);
};
watch(
  () => props.approvalVisiable,
  (newValue, oldValue) => {
    if (newValue) {
      getTpye();
      // changeType();
    }
  }
);
</script>

<style lang="scss" scoped>
.title {
  text-align: center;
  margin: 0;
  color: $theme-primary;
}
.approval-box {
  display: flex;
  width: 300px;
  align-items: flex-end;
  text-align: left;
  color: $theme-primary;
  margin-bottom: 25px;
}
.space {
  :deep(.ant-form-item-control-input-content) {
    display: flex;
    align-items: center;
  }
  :deep(.ant-form-item-control-input-content) {
    max-width: 100%;
  }
}
:deep(.ant-input-number-handler-wrap) {
  display: none;
}
:deep(.ant-input-number) {
  width: 100%;
}
.form-label {
  font-size: 16px;
  color: $theme-primary;
}
.tags {
  background-color: #cfcad8;
  width: 422px;
  margin-left: 109px;
}
:deep(.ant-timeline-item-last > .ant-timeline-item-content) {
  min-height: 0;
}
:deep(.ant-picker-input > input[disabled]) {
  color: black;
}
:deep(.ant-timeline-item-last) {
  padding-bottom: 0;
}
.textarea {
  background-color: #cfcad8;
}
textarea::-webkit-input-placeholder {
  color: #ffffff !important;
}
.button-group {
  text-align: center;
}
.action-table {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.cancel-btn {
  width: 123px;
  border-radius: 20px;
  background: #eeeaf7;
  margin-right: 10px;
  color: $theme-primary;
}
.save-btn {
  width: 123px;
  border-radius: 20px;
  background: $theme-primary;
  color: #ffff;
}
:deep(.ant-space) {
  display: block;
}

.artwork-table {
  :deep(.ant-table) {
    border-radius: 1px;
    overflow: hidden;
    color: $basic-black;
  }

  :deep(.ant-table-container) {
    border: 1px solid #cfcad8;
  }
  :deep(.ant-table-thead > tr > th) {
    padding: 4px 4px;
  }
  :deep(.ant-table-tbody > tr > td) {
    padding: 4px 16px;
  }
  :deep(.ant-table-thead > tr > th) {
    background: #cfcad8 !important;
    border-bottom: 1px solid #dfd7f2;
    font-weight: bolder !important;
    color: #7161a5 !important;
  }
}
:deep(.ant-form-item-label > label) {
  color: $theme-primary;
  font-size: 16px;
  font-weight: 400;
}

:deep(.ant-form-item) {
  color: $theme-primary;
  font-size: 16px;
  font-weight: 200;
  .ant-select {
    background-color: #e3dfea;
  }
  .ant-input {
    background-color: #e3dfea;
  }
  .ant-select-arrow .anticon {
    color: $theme-primary;
  }
}
</style>
<style lang="scss">
.drop-down {
  width: 370px !important;
}
.approval-out-dialog {
  width: 1100px !important;
  .ant-modal-body {
    height: 700px !important;
    overflow: scroll;
    overflow-x: hidden;
  }
}
</style>
